Last active
March 9, 2018 15:49
-
-
Save antelle/4a6a346eb65678a24c5716c33ed06786 to your computer and use it in GitHub Desktop.
JS string escape
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
function escape(str) { | |
return str.replace(/[\n\r\\\'\u2028\u2029]/g, ch => { | |
if (ch === '\n') { return '\\n'; } | |
else if (ch === '\r') { return '\\r'; } | |
else if (ch === '\\') { return '\\\\'; } | |
else if (ch === '\'') { return '\\\''; } | |
else if (ch === '\u2028') { return '\\u2028'; } | |
else if (ch === '\u2029') { return '\\u2029'; } | |
else throw 'Bad char'; | |
}); | |
} | |
// example | |
const escaped = escape(data); | |
const code = `xxx = '${escaped}';`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment