Is there a better way to concatenate strings that have "'s (such as HTML tag attribute definitions) in jQuery than escaping the quote?
Escapy Example:
$(this).prepend("<label for=\""+$(this).attr("id")+"\">"+"a"+"</label>");
In Python, such sequence of characters is included inside single or double quotes. As far as language syntax is concerned, there is no difference in single or double quoted string. Both representations can be used interchangeably.
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!
When you concatenate text, you surround the text with double quotation marks so Microsoft Excel recognizes it as text. Otherwise, you'll receive an error. Excel then uses the text within quotes but discards the quotation marks.
You can use the object method of creation ($(html, props)
), like this:
$('<label />', { for: this.id, text: 'a' }).prependTo(this);
//or:
$(this).prepend($('<label />', { for: this.id, text: 'a' }));
This has the advantage of calling .text()
internally, taking care of any encoding issues. Also, if you're doing this a lot, it'll be faster, since the HTML fragment is consistent and cached, so a clone of the node is used, rather than turning a string into a document fragment each time. The more elements like this you're creating, the faster it is over the string method. For the same caching reasons, the bigger the element (up to a 512 char string) the bigger the gains.
you can use single quotes for the main string and then you don't have to escape the double quote.
$(this).prepend('<label for="'+$(this).attr("id")+'">'+ a +'</label>');
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