1

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

version 2
  • 1,049
  • 3
  • 15
  • 36

3 Answers3

4

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

Use the substring method:

var s="";
for(var i=1;i<=10;i++)
{
    s=s+"'"+"id"+i+"',";
}
s = s.substring(0, s.length - 1);
document.write(s);
nweg
  • 2,825
  • 3
  • 22
  • 30
1

using JavaScript String slice() method

str.slice(0,-1);

The slice() method extracts a section of a string and returns a new string - MDN doc

Nin-ya
  • 252
  • 1
  • 12