-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathattr.parser.js
More file actions
48 lines (45 loc) · 1.32 KB
/
attr.parser.js
File metadata and controls
48 lines (45 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const Parser = require('fastparse');
/**
* Process attr match
* @param {string} match - matched value
* @param {string} orig - origin value
* @param {string} attr - attribute name
* @param {string} value - attribute value
* @param {number} index - match index
*/
function processMatch(match, orig, attr, value, index) {
if (!this.filterAttr(this.currentTag, attr)) return;
this.results.push({
start: index + orig.length,
length: value.length,
value,
tag: this.currentTag,
attr,
});
}
const parser = new Parser({
outside: {
'<!--.*?-->': true,
'<![CDATA[.*?]]>': true,
'<[!\\?].*?>': true,
'<\\/[^>]+>': true,
'<([a-zA-Z\\-:]+)\\s*': function insideTag(match, tagName) {
this.currentTag = tagName;
return 'inside';
},
},
inside: {
'\\s+': true, // eat up whitespace
'>': 'outside', // end of attributes
'(([0-9a-zA-Z\\-:]+)\\s*=\\s*")([^"]*)"': processMatch,
"(([0-9a-zA-Z\\-:]+)\\s*=\\s*')([^']*)'": processMatch,
'(([0-9a-zA-Z\\-:]+)\\s*=\\s*)([^\\s>]+)': processMatch,
},
});
module.exports = function attrParser(html, filterAttr) {
return parser.parse('outside', html, {
currentTag: null,
results: [],
filterAttr,
}).results;
};