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.
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.
When using double quotes "" to create a string literal, the double quote character needs to be escaped using a backslash: \" .
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.
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!
If it is HTML, you can use HTML entities to escape characters that might be interpreted otherwise. For example, "
will be displayed as "
in HTML attributes:
var content = '<input type="text" ng-model="test1" />';
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With