-
-
Save tonykwok/c4ef60d06c763286b3a2f9168f0d2967 to your computer and use it in GitHub Desktop.
escape all (not-already-escaped) double-quote chars in a string
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
// 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