views:

72

answers:

5

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

+5  A: 

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>');
Jeff T
+1  A: 

Single quotes?

$(this).prepend('<label for="'+$(this).attr("id")+'">'+'a'+'</label>');

or, jQuery:

$("<label>").attr("for", this.id).text(a).prependTo(this);
Tomalak
+6  A: 

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.

Nick Craver
+1 Nice alternative.
patrick dw
far more readable too
box9
+1 for jQuery internal fragment caching fu
jmar777
yes +1 and +selected for caching fu
ina
+4  A: 

This is why I primarily use single quotes $('here'). Less to worry about when you're working with HTML that inevitably is full of double quotes.

$('""""No worries!"""""""')

The Google JavaScript Style Guide agrees.

Ken Redler
what if you have html with words like `"Ben Franklin's kite"`?
ina
Well, then you're back to escaping. Nothing's perfect, right? May as well code to make the most common case easier.
Ken Redler
+1  A: 

Single quotes are definitely the way to go. I recommend using them for all strings in javascript. Particularly when working with jQuery, it is much more common to need to use a double quote inside a string than a single quote, so it will save you a lot of time escaping and improve readability. Additionally, it'll save you keystrokes, no more pesky shift key :)

Ender