Skip to content

Commit

Permalink
fix(escape_html): avoid double escape (#328)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenjoezhang authored Jul 10, 2023
1 parent b33894d commit 5195be9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
16 changes: 9 additions & 7 deletions lib/escape_html.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import unescapeHTML from './unescape_html';

const htmlEntityMap = {
const escapeTestNoEncode = /[<>"'`/=]|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');
const escapeReplacements = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
Expand All @@ -10,14 +10,16 @@ const htmlEntityMap = {
'/': '&#x2F;',
'=': '&#x3D;'
};
const getEscapeReplacement = (ch: string) => escapeReplacements[ch];

function escapeHTML(str: string) {
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]);
// https://github.com/markedjs/marked/blob/master/src/helpers.js
if (escapeTestNoEncode.test(str)) {
return str.replace(escapeReplaceNoEncode, getEscapeReplacement);
}
return str;
}

export = escapeHTML;
4 changes: 4 additions & 0 deletions test/escape_html.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@ describe('escapeHTML', () => {
it('avoid double escape', () => {
escapeHTML('&lt;foo>bar</foo&gt;').should.eql('&lt;foo&gt;bar&lt;&#x2F;foo&gt;');
});

it('avoid double escape https://github.com/hexojs/hexo/issues/4946', () => {
escapeHTML('&emsp;&nbsp;&ensp;').should.eql('&emsp;&nbsp;&ensp;');
});
});

0 comments on commit 5195be9

Please sign in to comment.