The simple code block below can be served up in a static HTML page but results in a JavaScript error. How should you escape the embedded double quote in the onClick
handler (i.e. "xyz)? Note that the HTML is generated dynamically by pulling data from a database, the data of which is snippets of other HTML code that could have either single or double quotes. It seems that adding a single backslash ahead of the double quote character doesn't do the trick.
<script type="text/javascript"> function parse(a, b, c) { alert(c); } </script> <a href="#x" onclick="parse('#', false, '<a href=\"xyz'); return false">Test</a>
To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it' . Copied!
Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.
Did you try
"
or \x22
instead of
\"
?
It needs to be HTML-escaped, not Javascript-escaped. Change \"
to "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With