Escaping double quotes in JavaScript onClick event handler

user133046 picture user133046 · Jul 4, 2009 · Viewed 101.4k times · Source

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>

Answer

Landon Kuhn picture Landon Kuhn · Jul 4, 2009

Did you try

&quot; or \x22

instead of

\"

?