Skip to content

Instantly share code, notes, and snippets.

@chakhsu
Created May 7, 2017 01:51
Show Gist options
  • Save chakhsu/2bf944e7db9cbeab1f473596f1561505 to your computer and use it in GitHub Desktop.
Save chakhsu/2bf944e7db9cbeab1f473596f1561505 to your computer and use it in GitHub Desktop.
[Escaped Chars] #HTML #JavaScript
"use strict";
const HTML_ESCAPED_CHARS = {
"<" : "&lt;",
">" : "&gt;",
"\"": "&quot;",
"&" : "&amp;",
"'" : "&#39;",
"/" : "&#47;",
"`" : "&#96;",
};
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