Skip to content

Instantly share code, notes, and snippets.

@frankpf
Created February 25, 2021 17:56
Show Gist options
  • Save frankpf/87c8209a571d662cd8bcee65e430c9e4 to your computer and use it in GitHub Desktop.
Save frankpf/87c8209a571d662cd8bcee65e430c9e4 to your computer and use it in GitHub Desktop.
const UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g
const ESCAPED_CHARS = {
'<' : '\\u003C',
'>' : '\\u003E',
'/' : '\\u002F',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
}
function escapeUnsafeChars(unsafeChar) {
return ESCAPED_CHARS[unsafeChar]
}
function safeStringify(input) {
const rawString = JSON.stringify(input)
return rawString.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars)
}
var input = { a: "<script>alert(123)</script>" }
var output = safeStringify({ "a": "<script>alert(123)</script>" })
console.log(output)
// => {"a":"\u003Cscript\u003Ealert(123)\u003C\u002Fscript\u003E"}"
var roundtrip = JSON.parse(output)
console.log(roundtrip.a == input.a)
// => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment