Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping double double quotes in html attributes in Javascript

I use bootstrap and create html nodes which contain popovers with jQuery. The popovers contain html so that I have problems with the quotes and escaping:

var content = '<input type="text" ng-model="test1" />';
var txt =     '<button type="button" data-container="body" ' +
                     'data-toggle="popover" title="myTitle" data-html="true" '+
                     'data-content="'+content+'">Click</button>';

How can I escape the double quotes inside the attributes => html-attributes? in the data-content attribute correctly?

Edit: I compile the code with angular so that it should also work with it.

like image 856
daniel Avatar asked Aug 02 '14 10:08

daniel


People also ask

How do you escape a double quote in JavaScript?

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 in HTML?

When using double quotes "" to create a string literal, the double quote character needs to be escaped using a backslash: \" .

Do HTML attributes need double quotes?

The HTML specification says: Attributes are placed inside the start tag, and consist of a name and a value, separated by an = character. The attribute value can remain unquoted if it doesn't contain spaces or any of " ' ` = < or > . Otherwise, it has to be quoted using either single or double quotes.

Can you use double quotes in JavaScript?

Both single (' ') and double (" ") quotes are used to represent a string in Javascript. Choosing a quoting style is up to you and there is no special semantics for one style over the other. Nevertheless, it is important to note that there is no type for a single character in javascript, everything is always a string!


1 Answers

If it is HTML, you can use HTML entities to escape characters that might be interpreted otherwise. For example, &quot; will be displayed as " in HTML attributes:

var content = '<input type=&quot;text&quot; ng-model=&quot;test1&quot; />';

Proof of concept: http://jsfiddle.net/teddyrised/5X5Ye/

Refer to W3C's HTML entities chart for more information: http://dev.w3.org/html5/html-author/charref

like image 148
Terry Avatar answered Oct 05 '22 10:10

Terry