Skip to content

Instantly share code, notes, and snippets.

@getify
Last active June 25, 2022 16:26
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save getify/3667624 to your computer and use it in GitHub Desktop.
Save getify/3667624 to your computer and use it in GitHub Desktop.
escape all (not-already-escaped) 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 (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
@jhallal
Copy link

jhallal commented Apr 12, 2022

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