diff --git a/lib/escape_html.js b/lib/escape_html.js index 512243e1..5711aa95 100644 --- a/lib/escape_html.js +++ b/lib/escape_html.js @@ -2,7 +2,7 @@ const unescapeHTML = require('./unescape_html'); -const htmlEntityMap = { +/* const htmlEntityMap = { '&': '&', '<': '<', '>': '>', @@ -11,7 +11,7 @@ const htmlEntityMap = { '`': '`', '/': '/', '=': '=' -}; +}; */ function escapeHTML(str) { if (typeof str !== 'string') throw new TypeError('str must be a string!'); @@ -19,7 +19,19 @@ function escapeHTML(str) { str = unescapeHTML(str); // http://stackoverflow.com/a/12034334 - return str.replace(/[&<>"'`/=]/g, a => htmlEntityMap[a]); + // return str.replace(/[&<>"'`/=]/g, a => htmlEntityMap[a]); + + // Multiple replacement is 3x faster than map replacement. + // Benchmark: https://runkit.com/sukkaw/5e3003ffe7e84c0013f6210d + return str + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') + .replace(/`/g, '`') + .replace(/\//g, '/') + .replace(/=/g, '='); } module.exports = escapeHTML; diff --git a/lib/unescape_html.js b/lib/unescape_html.js index e83d4ba3..11b66476 100644 --- a/lib/unescape_html.js +++ b/lib/unescape_html.js @@ -1,22 +1,17 @@ 'use strict'; -const htmlEntityMap = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': '\'', - '`': '`', - '/': '/', - '=': '=' -}; - -const regexHtml = new RegExp(Object.keys(htmlEntityMap).join('|'), 'g'); - const unescapeHTML = str => { if (typeof str !== 'string') throw new TypeError('str must be a string!'); - return str.replace(regexHtml, a => htmlEntityMap[a]); + return str + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, '\'') + .replace(/`/g, '`') + .replace(///g, '/') + .replace(/=/g, '='); }; module.exports = unescapeHTML;