Escaping double quotes in JavaScript onClick event handler
dom-events, escaping, html, javascript
Solution
Did you try
`"` or `\x22`
instead of
\"
?
Problem
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> ```