Skip to content

Commit

Permalink
Only invoke String.replace() once during decode. (fixes gh fb55#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
cscott committed Apr 18, 2013
1 parent 6ad621f commit ab41f93
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
14 changes: 10 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var re_hex = /&#x[\da-f]+;?/gi,
var re_hex = /&#[xX][\da-fA-F]+;?/g,
re_strictHex = /&#x[\da-f]+;/gi,
re_charCode = /&#\d+;?/g,
re_strictCharCode = /&#\d+;/g,
Expand All @@ -16,9 +16,17 @@ var fetch = function(filename, inherits){
if(inherits) for(var name in inherits) obj[name] = inherits[name];

var re = Object.keys(obj).sort().join("|").replace(/(\w+)\|\1;/g, "$1;?");
// add regex for hex and char codes
re += '|' + re_hex.source.substr(1) + '|' + re_charCode.source.substr(1);

return {
func: function(name){
if (name.charAt(1) === '#') {
if (name.charAt(2).toLowerCase() === 'x') {
return hex_func(name);
}
return num_func(name);
}
return obj[name.substr(1)];
},
re: new RegExp("&(?:" +re +")", "g"),
Expand Down Expand Up @@ -62,9 +70,7 @@ modes.forEach(function(name){

module.exports["decode" +name] = function(data){
return data
.replace(regex, func)
.replace(re_hex, hex_func)
.replace(re_charCode, num_func);
.replace(regex, func);
};

var reverse = getReverse(obj.obj),
Expand Down
29 changes: 28 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
var assert = require('assert');
var entities = require('../');

describe("Encode/decode test", function() {
describe("Encode->decode test", function() {
var testcases = [
{ input: "asdf & ÿ ü '",
xml: "asdf & ÿ ü '",
Expand Down Expand Up @@ -36,3 +36,30 @@ describe("Encode/decode test", function() {
});
});
});

describe("Decode test", function() {
var testcases = [
{ input: '&', output: '&' },
{ input: '&', output: '&' },
{ input: '&', output: '&' },
{ input: '&', output: '&' },
{ input: '&', output: '&' },
{ input: '&', output: '&' },
{ input: '&', output: '&' },
{ input: ':', output: ':' },
{ input: ':', output: ':' },
{ input: ':', output: ':' },
{ input: ':', output: ':' }
];
testcases.forEach(function(tc) {
it('should XML decode '+tc.input, function() {
assert.equal(entities.decodeXML(tc.input), tc.output);
});
it('should HTML4 decode '+tc.input, function() {
assert.equal(entities.decodeHTML4(tc.input), tc.output);
});
it('should HTML5 decode '+tc.input, function() {
assert.equal(entities.decodeHTML5(tc.input), tc.output);
});
});
});

0 comments on commit ab41f93

Please sign in to comment.