Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I concatenate multiline string in javascript?

There are lots of results for the correct syntax for appending <li>'s, however I am trying to find a solution where +this['name']+ values are included in the <li>'s. firebug is displaying 'SyntaxError: unterminated string literal' and jslint is displaying 'Unclosed string'. I've tried many different variations of the placements of the commas but I haven't been able to get it to work.

 $.each(data.result, function() {
     $("ul").append("<li>Name: "+this['name']+"</li>
                     <li>Age: "+this['age']+"</li>
                     <li>Company: "+this['company']+"</li>
                     <br />");
 });

Thank you.

like image 979
user1063287 Avatar asked Dec 20 '22 14:12

user1063287


1 Answers

you can escape end of line with backslash character \, like so:

 $.each(data.result, function(){
 $("ul").append("<li>Name: " + this['name'] + "</li> \
     <li>Age: " + this['age'] + "</li> \
     <li>Company: "+this['company']+"</li> \
     <br />");
 });

This is due to the fact that Javascript automatically insert semi-columns sometime on line end. And in this case, you string weren't close. Another solution is to close each string on each line, and using + to concat them all.

 $.each(data.result, function(){
 $("ul").append("<li>Name: " + this['name'] + "</li>" +
     "<li>Age: " + this['age'] + "</li>" +
     "<li>Company: "+this['company']+"</li>" +
     "<br />");
 });

(Unrelated, but you <br/> aren't allowed inside a <ul> element)

like image 198
Simon Boudrias Avatar answered Jan 11 '23 23:01

Simon Boudrias