Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping double quotes in JavaScript onClick event handler

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> 
like image 991
user133046 Avatar asked Jul 04 '09 05:07

user133046


People also ask

How do you escape a double quote in JavaScript?

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!

How do you skip quotes in JavaScript?

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.

How do you escape a double quote?

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.


2 Answers

Did you try

&quot; or \x22

instead of

\" 

?

like image 53
Landon Kuhn Avatar answered Sep 22 '22 07:09

Landon Kuhn


It needs to be HTML-escaped, not Javascript-escaped. Change \" to &quot;

like image 25
Aseem Kishore Avatar answered Sep 21 '22 07:09

Aseem Kishore