speedy-entities
Version:
The fastest XML/HTML entities decoder.
30 lines (29 loc) • 888 B
JavaScript
const re = /["&'<>]/g;
export function escapeXML(input) {
let output = '';
let textIndex = 0;
while (re.test(input)) {
const lastIndex = re.lastIndex;
const startIndex = lastIndex - 1;
const charCode = input.charCodeAt(startIndex);
let entity;
if (charCode === 34) {
entity = '"';
}
else if (charCode === 38) {
entity = '&';
}
else if (charCode === 39) {
entity = ''';
}
else if (charCode === 60) {
entity = '<';
}
else {
entity = '>';
}
output += textIndex === startIndex ? entity : input.slice(textIndex, startIndex) + entity;
textIndex = lastIndex;
}
return textIndex === 0 ? input : textIndex === input.length ? output : output + input.slice(textIndex);
}