constructing long string with Javascript

There is a time you need to construct a string (for instance, to create a html block) in your code.

In the simpliest approach, youcan constract the string variable  like so

var html='<head><body>’+contentVariable+’more stuff’ + ‘</body></head>’;

this becomes very messy quickly once more variables, more nested construction is needed.

I used to keep concatinating the string, like so

var html='<head></body>’;

html +=  contentVariable;

html += ‘ more Stuff’;

html += ‘</body></head>’;



Then I saw a pattern in the couple of codes from internet;

var h=[‘<head><body’];


h.push(‘more Stuff’);


var html=h.join(”);

The More concatenation needed, the more convinient the last method becomes. Key is to join the array element with null delimiter.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.