-
-
Save Raidus/5bccebc803d0eda974bb1468431c6600 to your computer and use it in GitHub Desktop.
escape all 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 | |
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