Skip to content

Commit

Permalink
Merge 087af71 into 4e7c24e
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Jan 28, 2020
2 parents 4e7c24e + 087af71 commit 520080f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
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;

0 comments on commit 520080f

Please sign in to comment.