Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - better way to concatenate strings that have quotations?

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>");

like image 773
ina Avatar asked Aug 11 '10 22:08

ina


People also ask

Are single quotes more pythonic?

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.

Is single quote or double quote better 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!

Why is concatenate adding quotes?

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.


2 Answers

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.

like image 184
Nick Craver Avatar answered Oct 24 '22 03:10

Nick Craver


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>');
like image 29
Jeff Treuting Avatar answered Oct 24 '22 02:10

Jeff Treuting