Created
May 7, 2017 01:51
-
-
Save chakhsu/2bf944e7db9cbeab1f473596f1561505 to your computer and use it in GitHub Desktop.
[Escaped Chars] #HTML #JavaScript
This file contains hidden or 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
"use strict"; | |
const HTML_ESCAPED_CHARS = { | |
"<" : "<", | |
">" : ">", | |
"\"": """, | |
"&" : "&", | |
"'" : "'", | |
"/" : "/", | |
"`" : "`", | |
}; | |
const HTML_UNSAFE_CHARS_REGEXP = /[<>"\\&'\/`]/g; | |
const JS_ESCAPED_CHARS = { | |
"<" : "\\u003C", | |
">" : "\\u003E", | |
"/" : "\\u002F", | |
"\u2028": "\\u2028", | |
"\u2029": "\\u2029", | |
}; | |
const JS_UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g; | |
export function outputToHTML(str) { | |
return str.replace(HTML_UNSAFE_CHARS_REGEXP, ch => HTML_ESCAPED_CHARS[ch]); | |
} | |
export function outputToJS(str) { | |
return JSON.stringify(str) | |
.replace(JS_UNSAFE_CHARS_REGEXP, ch => JS_ESCAPED_CHARS[ch]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment