Last active
June 25, 2022 16:26
-
-
Save getify/3667624 to your computer and use it in GitHub Desktop.
escape all (not-already-escaped) double-quote chars in a string
This file contains 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 |
THanks this is a good one
When you need to use both single and double quotes in the string you can use the following solutions to escape the quotes:
- " becomes "
- ' becomes '
Keep in mind that you will never need to escape more than the following five special characters:
- & becomes &
- < becomes <
- becomes >
- " becomes "
- ' becomes '
Once you have these escaped you should never have an issue with broken values in HTML again.
Reference: https://jamilhallal.blogspot.com/2022/04/javascript-escape-quotes.html
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks this worked !!!