Skip to content

Instantly share code, notes, and snippets.

@voxpelli
Last active August 25, 2021 14:45
Show Gist options
  • Select an option

  • Save voxpelli/ff7a83406078ba2d68b738e63cad6498 to your computer and use it in GitHub Desktop.

Select an option

Save voxpelli/ff7a83406078ba2d68b738e63cad6498 to your computer and use it in GitHub Desktop.
HTML safe JSON escaping, see eg: https://github.com/ember-fastboot/fastboot/pull/85
// My own take
const JSON_ESCAPE = {
'&': '\\u0026',
'>': '\\u003e',
'<': '\\u003c',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};
const JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/g;
const escapeJSONString = (obj) =>
JSON.stringify(obj)
.replace(JSON_ESCAPE_REGEXP, match => JSON_ESCAPE[match]);
// Extracted from https://github.com/ember-fastboot/ember-cli-fastboot/blob/909c1417ceeb8a5c92bb952b0d59be02bfdca546/packages/fastboot/src/ember-app.js#L406-L420
const JSON_ESCAPE = {
'&': '\\u0026',
'>': '\\u003e',
'<': '\\u003c',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};
const JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/g;
function escapeJSONString(string) {
return string.replace(JSON_ESCAPE_REGEXP, function(match) {
return JSON_ESCAPE[match];
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment