Skip to content

Commit eddb606

Browse files
Merge pull request #181 from preactjs/escape-perf
Perf: Improve HTML entity escaping
2 parents 5f0edc2 + 5a8d018 commit eddb606

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

src/util.js

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
11
// DOM properties that should NOT have "px" added when numeric
22
export const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|^--/i;
33

4+
const HTML_ENTITY_REG = /[&<>"]/g;
5+
const tagsToReplace = {
6+
'&': '&amp;',
7+
'<': '&lt;',
8+
'>': '&gt;',
9+
'"': '&quot;'
10+
};
11+
const replaceTag = (tag) => tagsToReplace[tag] || tag;
412
export function encodeEntities(s) {
513
if (typeof s !== 'string') s = String(s);
6-
let out = '';
7-
for (let i = 0; i < s.length; i++) {
8-
let ch = s[i];
9-
// prettier-ignore
10-
switch (ch) {
11-
case '<': out += '&lt;'; break;
12-
case '>': out += '&gt;'; break;
13-
case '"': out += '&quot;'; break;
14-
case '&': out += '&amp;'; break;
15-
default: out += ch;
16-
}
17-
}
18-
return out;
14+
return s.replace(HTML_ENTITY_REG, replaceTag);
1915
}
2016

2117
export let indent = (s, char) =>

0 commit comments

Comments
 (0)