Saturday, 18 June 2016

How to remove extra character added while concatinating string in a loop in JavaScript?




am concatinating a string inside a for loop



var s="";
for(var i=1;i<=10;i++)
{
s=s+"'"+"id"+i+"',";
}
document.write(s);



Output I got is



'id1','id2','id3','id4','id5','id6','id7','id8','id9','id10',


I am trying to get the result as



'id1','id2','id3','id4','id5','id6','id7','id8','id9','id10'



How can I remove the extra , added an the end?



Fiddle


Answer



You can use a array of strings and then join the string like



var s = [];
for (var i = 1; i <= 10; i++) {

s.push("'id" + i + "'");
}
var string = s.join();


Demo: Fiddle


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...