Created
February 25, 2021 17:56
-
-
Save frankpf/87c8209a571d662cd8bcee65e430c9e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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