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

0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.