-
-
Save getify/3667624 to your computer and use it in GitHub Desktop.
// 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 |
@WebReflection, you're still misquoting both the regex and the replacement string. To mark text as code in GitHub comments, put it between grave accent characters.
@getify, for the record, my solution can easily be adapted for other characters that need to be escaped, by simply changing the character or list of characters matched within capturing group 2. E.g., to escape unescaped letters:
str.replace(/\\([\s\S])|([a-z])/ig, "\\$1$2")
thanks for explanation, so we could use the same regex to escape any character or group of character, I used for single and double quotes escape.
str.replace(/\([\s\S])|(['"])/ig, "\$1$2")
Thanks for sharing @getify
However, If the escaped string would be injected into HTML markup, you need the following version of the function:
function encodeHTML(s) {
return s.split('&').join('&').split('<').join('<').split('"').join('"').split("'").join(''');
}
Source: Are single/double quotes allowed inside HTML attribute values? - Stack Overflow
Thanks this worked !!!
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
uhm ....
'\\"'.replace(/\\([\s\S])|(")/g,"\\$1$2") === '\\"'