Skip to content

Commit

Permalink
Added support for interpreting numeric entities when the charset is i…
Browse files Browse the repository at this point in the history
…so-8859-1, eg. &#9786 => ☺.

This is what browsers send when the user tries to submit characters that aren't available in the charset being used to submit the form.
  • Loading branch information
papandreou committed Jul 16, 2018
1 parent 95653c0 commit df77dfd
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
17 changes: 14 additions & 3 deletions lib/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ var defaults = {
strictNullHandling: false
};

var interpretNumericEntities = function (str) {
return str.replace(/&#(\d+);/g, function ($0, numberStr) {
return String.fromCharCode(parseInt(numberStr, 10));
});
};

var parseValues = function parseQueryStringValues(str, options) {
var obj = {};
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
Expand Down Expand Up @@ -43,10 +49,15 @@ var parseValues = function parseQueryStringValues(str, options) {
} else if (val === '✓') {
charset = 'iso-8859-1';
}
} else if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
if (options.interpretNumericEntities && charset === 'iso-8859-1') {
val = interpretNumericEntities(val);
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
}

Expand Down
15 changes: 15 additions & 0 deletions test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -607,5 +607,20 @@ test('parse()', function (t) {
st.end();
});

t.test('interprets numeric entities in iso-8859-1 when the interpretNumericEntities option is given', function (st) {
st.deepEqual(qs.parse('foo=%26%239786%3B', { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '☺' });
st.end();
});

t.test('does not interpret numeric entities in iso-8859-1 when the interpretNumericEntities option is not given', function (st) {
st.deepEqual(qs.parse('foo=%26%239786%3B', { charset: 'iso-8859-1' }), { foo: '☺' });
st.end();
});

t.test('does not interpret numeric entities when the charset is utf-8, even when the interpretNumericEntities option is given', function (st) {
st.deepEqual(qs.parse('foo=%26%239786%3B', { charset: 'utf-8', interpretNumericEntities: true }), { foo: '☺' });
st.end();
});

t.end();
});

0 comments on commit df77dfd

Please sign in to comment.