Skip to content

Instantly share code, notes, and snippets.

@Raidus
Forked from getify/gist:3667624
Created June 30, 2020 11:24
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 Raidus/5bccebc803d0eda974bb1468431c6600 to your computer and use it in GitHub Desktop.
Save Raidus/5bccebc803d0eda974bb1468431c6600 to your computer and use it in GitHub Desktop.
escape all 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
escapeDoubleQuotes("a\"b"); // a"b => a\"b
escapeDoubleQuotes("a\\\"b"); // a\"b => a\"b
escapeDoubleQuotes("a\\\\\"b"); // a\\"b => a\\\"b
escapeDoubleQuotes("a\\\\\\\"b"); // a\\\"b => a\\\"b
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