Skip to content

Commit 60431d9

Browse files
Merge pull request #170 from preactjs/opt-entity-encoding
Optimize HTML entity encoding
2 parents fe749fb + 51e91c8 commit 60431d9

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

src/util.js

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,22 @@
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-
export let encodeEntities = s => String(s)
5-
.replace(/&/g, '&')
6-
.replace(/</g, '&lt;')
7-
.replace(/>/g, '&gt;')
8-
.replace(/"/g, '&quot;');
4+
export function encodeEntities(s) {
5+
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+
switch (ch) {
10+
case '<': out += '&lt;'; break;
11+
case '>': out += '&gt;'; break;
12+
case '"': out += '&quot;'; break;
13+
case '&': out += '&amp;'; break;
14+
default: out += ch;
15+
}
16+
}
17+
return out;
18+
}
19+
920

1021
export let indent = (s, char) => String(s).replace(/(\n+)/g, '$1' + (char || '\t'));
1122

0 commit comments

Comments
 (0)