Blog archives

Easy concatenation in Javascript

When developing stuff in Javascript and jQuery you often need to concat lots of HTML for output. That gets ugly pretty fast.

$("#mydiv").html('<div id="lightbox-container-image-data-box">' +
this.something + '<div id="lightbox-container-image-data"><div' + 
'id="lightbox-image-details"><span id="lightbox-image-details-caption">' +
v + '</span><span id="lightbox-image-details-currentNumber"></span>' + 
'</div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose">' + 
'<img src="'+settings.imageBtnClose+'">');

There are a few different ways to concat strings in Javascript and make your code more readable.

Using the + operator:

var html = "<table>" + 
    "<tr>" + 
    "<td>" +
    "</td>" + 
    "</tr>" + 
    "</table>";

I don’t like this notation. To make it readable you need an extra space after the closing " and you can’t nicely line up all the strings.

Another way is using the Array.join("") method:

var html = [
    "<table>",
    "<tr>",
    "<td>",
    "</td>",
    "</tr>",
    "</table>"
].join("");

This has the disadvantage that you need a method at the end of the array, and in modern browsers it is a little slower than native concatting.

Another way is using the String.concat() method

var html = (new String("")).concat(
    "<table>",
    "<tr>",
    "<td>",
    "</td>",
    "</tr>",
    "</table>"
);

I especially like this last method. Unfortunately the syntax is a little clunky. My colleague Frank suggested a slightly different notation

var html = ''.concat(
    "<table>",
    "<tr>",
    "<td>",
    "</td>",
    "</tr>",
    "</table>"
);

This is valid because '' is equivalent to (new String(“”)). This works great and makes passing HTML as an argument to jQuery methods a lot more readable:

$("#mydiv").html(''.concat(
    '<table>",
    '<tr><td>',
    '</td></tr>',
    '</table>'
));

Add a comment