Skip to content
This repository was archived by the owner on Jan 7, 2021. It is now read-only.

Commit 877dbe5

Browse files
committed
Merge pull request #113 from erikbern/master
Fix sanitize for text
2 parents cb3ba8c + ed899f1 commit 877dbe5

File tree

5 files changed

+21
-4
lines changed

5 files changed

+21
-4
lines changed

lib/sanitize.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,17 @@ function escapeRegExp(string) {
2727
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
2828
}
2929

30-
exports.sanitize = function sanitize(value) {
30+
exports.sanitize = function sanitize(value, reverse) {
3131
if (typeof value !== 'string') {
3232
return value;
3333
}
3434

3535
Object.keys(chars).forEach(function(key) {
36-
value = value.replace(new RegExp(escapeRegExp(key), 'g'), chars[key]);
36+
if (reverse) {
37+
value = value.replace(new RegExp(escapeRegExp(chars[key]), 'g'), key);
38+
} else {
39+
value = value.replace(new RegExp(escapeRegExp(key), 'g'), chars[key]);
40+
}
3741
});
3842

3943
return value;

lib/xml2json.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ function endElement(name) {
6161
}
6262

6363
if (options.sanitize) {
64-
currentObject['$t'] = sanitizer.sanitize(currentObject['$t']);
64+
currentObject['$t'] = sanitizer.sanitize(currentObject['$t'], true);
6565
}
6666

6767
currentObject['$t'] = coerce(currentObject['$t'],name);

test/fixtures/xmlsanitize2.json

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"e":"Smith & Son"}

test/fixtures/xmlsanitize2.xml

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<e>Smith &amp; Son</e>

test/test.js

+12-1
Original file line numberDiff line numberDiff line change
@@ -88,14 +88,25 @@ describe('xml2json', function () {
8888
it('does xmlsanitize', function (done) {
8989

9090
var xml = internals.readFixture('xmlsanitize.xml');
91-
var result = parser.toJson(xml, {});
91+
var result = parser.toJson(xml, {sanitize: true});
9292
var json = internals.readFixture('xmlsanitize.json');
9393

9494
expect(result).to.deep.equal(json);
9595

9696
done();
9797
});
9898

99+
it('does xmlsanitize of text', function (done) {
100+
101+
var xml = internals.readFixture('xmlsanitize2.xml');
102+
var result = parser.toJson(xml, {sanitize: true});
103+
var json = internals.readFixture('xmlsanitize2.json');
104+
105+
expect(result).to.deep.equal(json);
106+
107+
done();
108+
});
109+
99110
it('throws error on bad options', function (done) {
100111

101112
var throws = function() {

0 commit comments

Comments
 (0)