Skip to content

Commit

Permalink
Refactor to avoid double unescape
Browse files Browse the repository at this point in the history
  • Loading branch information
Brent Ertz committed May 25, 2015
1 parent bdfe868 commit 8126cec
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 12 deletions.
43 changes: 31 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@
* Licensed under the MIT license.
*/

var chars = {
'&': '&',
'"': '"',
''': '\'',
'&lt;': '<',
'&gt;': '>'
};

/**
* Escape special characters in the given string of html.
*
Expand All @@ -14,12 +22,20 @@
*/
module.exports = {
escape: function(html) {
return String(html)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
if (!html) {
return '';
}

var values = Object.keys(chars).map(function(key) { return chars[key]; });
var re = new RegExp('(' + values.join('|') + ')', 'g');

return String(html).replace(re, function(match) {
for (var key in chars) {
if (chars.hasOwnProperty(key) && chars[key] === match) {
return key;
}
}
});
},

/**
Expand All @@ -29,11 +45,14 @@ module.exports = {
* @return {String}
*/
unescape: function(html) {
return String(html)
.replace(/&amp;/g, '&')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, '\'')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>');
if (!html) {
return '';
}

var re = new RegExp('(' + Object.keys(chars).join('|') + ')', 'g');

return String(html).replace(re, function(match) {
return chars[match];
});
}
};
16 changes: 16 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ describe('#escape', function() {
it('converts > into &gt;', function() {
escape('>').should.equal('&gt;');
});

it('returns empty string if called with falsey value', function() {
escape().should.equal('');
escape('').should.equal('');
escape(null).should.equal('');
});
});

describe('#unescape', function() {
Expand All @@ -45,4 +51,14 @@ describe('#unescape', function() {
it('converts &gt; into >', function() {
unescape('&gt;').should.equal('>');
});

it('does not double unescape values', function() {
unescape('&amp;quot;').should.equal('&quot;');
});

it('returns empty string if called with falsey value', function() {
unescape().should.equal('');
unescape('').should.equal('');
unescape(null).should.equal('');
});
});

0 comments on commit 8126cec

Please sign in to comment.