Skip to content

Instantly share code, notes, and snippets.

@tonykwok
Forked from getify/gist:3667624
Created February 22, 2021 07:31
Show Gist options
  • Save tonykwok/c4ef60d06c763286b3a2f9168f0d2967 to your computer and use it in GitHub Desktop.
Save tonykwok/c4ef60d06c763286b3a2f9168f0d2967 to your computer and use it in GitHub Desktop.
escape all (not-already-escaped) double-quote chars in a string
// NOTE: only escapes a " if it's not already escaped
function escapeDoubleQuotes(str) {
return str.replace(/\\([\s\S])|(")/g,"\\$1$2"); // thanks @slevithan!
}
escapeDoubleQuotes(`ab`); // ab => ab (nothing escaped)
escapeDoubleQuotes(`a"b`); // a"b => a\"b
escapeDoubleQuotes(`a\\"b`); // a\"b => a\"b (nothing escaped)
escapeDoubleQuotes(`a\\\\"b`); // a\\"b => a\\\"b
escapeDoubleQuotes(`a\\\\\\"b`); // a\\\"b => a\\\"b (nothing escaped)
escapeDoubleQuotes(`a"b"c`); // a"b"c => a\"b\"c
escapeDoubleQuotes(`a""b`); // a""b => a\"\"b
escapeDoubleQuotes(`""`); // "" => \"\"
// don't unnecessarily escape:
escapeDoubleQuotes(escapeDoubleQuotes(escapeDoubleQuotes(`a"b`))); // a"b => a\"b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment