Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting quotes in JavaScript/HTML

How do you nest quotes in HTML beyond the second level? As far as I know, there are only 2 types of quotes - single(') and double("). I am aware of escaping using slashes - you have to escape in the code but that escaping won't work at the browser level. What is the accepted method to get around something like the following?

<p onclick="exampleFunc('<div id="divId"></div>');">Some Text</p> 

That code prints to the browser:

');">Some Text

like image 233
Ryan Elkins Avatar asked Jun 14 '10 18:06

Ryan Elkins


People also ask

How do I embed a quote in HTML?

The HTML <q> tag defines a short quotation. Browsers normally insert quotation marks around the quotation.

How do you write a nested quote?

Use single quotes for a nested quotation, when someone repeats what someone else said. Joe smiled and said, "Jenny said 'yes' when I asked her to marry me." If you need another layer of quotation, just keep alternating between single and double quotation marks. "Joe was just here," said Susan.

How do you add quotes in JavaScript?

Enclosing Quotation Marks That means strings containing single quotes need to use double quotes and strings containing double quotes need to use single quotes. "It's six o'clock."; 'Remember to say "please" and "thank you."'; Alternatively, you can use a backslash \ to escape the quotation marks.

How do you display quotes in JavaScript?

Strings are created by putting data inside the quotes. JavaScript and other programming languages allow the users to keep the data either in double quotes (" ") or single quotes (' ').


2 Answers

You need to use proper escaping/encoding. Either in HTML using character references:

<p onclick="exampleFunc('&lt;div id=&quot;divId&quot;&gt;&lt;/div&gt;');">Some Text</p> 

Or in JavaScript using string escape sequences:

<p onclick="exampleFunc('\x3Cdiv\x20id\x3D\x22divId\x22\x3E\x3C/div\x3E');">Some Text</p> 
like image 81
Gumbo Avatar answered Sep 28 '22 10:09

Gumbo


Edit: this is not a solution for JavaScript in HTML, but for JavaScript only. My bad...

eval('eval(\"eval(\\\"alert(\\\\\\\"Now I\\\\\\\\\\\\\\\'m confused!\\\\\\\")\\\")\")'); 

Link. It's "recursive escaping".

like image 32
jonS90 Avatar answered Sep 28 '22 08:09

jonS90