Skip to content

Instantly share code, notes, and snippets.

@antelle
Last active March 9, 2018 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antelle/4a6a346eb65678a24c5716c33ed06786 to your computer and use it in GitHub Desktop.
Save antelle/4a6a346eb65678a24c5716c33ed06786 to your computer and use it in GitHub Desktop.
JS string escape
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