Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions lib/escape_html.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const unescapeHTML = require('./unescape_html');

const htmlEntityMap = {
/* const htmlEntityMap = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
Expand All @@ -11,15 +11,27 @@ const htmlEntityMap = {
'`': '&#96;',
'/': '&#x2F;',
'=': '&#x3D;'
};
}; */

function escapeHTML(str) {
if (typeof str !== 'string') throw new TypeError('str must be a string!');

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 faster than map replacement on Node.js 12 or later.
// Benchmark: https://runkit.com/sukkaw/5e3003ffe7e84c0013f6210d
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
.replace(/`/g, '&#96;')
.replace(/\//g, '&#x2F;')
.replace(/=/g, '&#x3D;');
}

module.exports = escapeHTML;
23 changes: 9 additions & 14 deletions lib/unescape_html.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
'use strict';

const htmlEntityMap = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': '\'',
'&#96;': '`',
'&#x2F;': '/',
'&#x3D;': '='
};

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(/&amp;/g, '&')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, '\'')
.replace(/&#96;/g, '`')
.replace(/&#x2F;/g, '/')
.replace(/&#x3D;/g, '=');
};

module.exports = unescapeHTML;