search

Home  >  Q&A  >  body text

How to escape double quotes in JavaScript's onClick event handler

<p>The simple code block below will work in a static HTML page, but will result in a JavaScript error. How should you escape the double quotes (i.e. "xyz") embedded in the <code>onClick</code> handler? Note that the HTML is dynamically generated by pulling data from the database that is the source of the other HTML code Fragment, may contain single or double quotes. It seems that adding a backslash before the double quote character does not solve the problem.</p> <pre class="brush:php;toolbar:false;"><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></pre>
P粉926174288P粉926174288513 days ago569

reply all(2)I'll reply

  • P粉709644700

    P粉7096447002023-08-23 12:17:11

    It requires HTML escaping, not Javascript escaping. Change \" to "

    reply
    0
  • P粉402806175

    P粉4028061752023-08-23 00:05:42

    Have you tried

    " or \x22

    instead of

    \"

    ?

    reply
    0
  • Cancelreply