Refactoring the old escape() function improved performance on 30-40%

This commit is contained in:
Костя Третяк 2018-01-03 11:25:44 +02:00 committed by KostyaTretyak
parent da942fd82f
commit eb9f08cbb3

View File

@ -1274,13 +1274,31 @@ Parser.prototype.tok = function() {
*/
function escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
if (encode) {
if (escape.escapeTest.test(html)) {
return html.replace(escape.escapeReplace, function (ch) { return escape.replacements[ch] });
}
} else {
if (escape.escapeTestNoEncode.test(html)) {
return html.replace(escape.escapeReplaceNoEncode, function (ch) { return escape.replacements[ch] });
}
}
return html;
}
escape.escapeTest = /[&<>"']/;
escape.escapeReplace = /[&<>"']/g;
escape.replacements = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
escape.escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
escape.escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
function unescape(html) {
// explicitly match decimal, hex, and named HTML entities