Simple Question? Alert text

Hello, I have some coursework in Javascript. Basically i have an array of pages and one question is a function to return a string containing the indexes in the pages array where variable string s was found in the content part

Example call:findIdxsC(“prog”)

Example result:“string s found in pages 0,3,5,6,9”

I have the code, which i’m pretty sure is correct…

at the start i have

x=“”
then a for loop… then if c=1, x = x + “,” + i

then an alert saying (‘"’ + s + " found " + “in pages " + x + '”');

It seems to work. However, the string result starts with a comma, the result shows

“string s found in pages ,0,3,5,6,9”

How do i get rid of the comma!? I have tried unsucessfully as i don’t know why it is there.

Thank you for reading and any help! Hope it makes sense.

The commas are coming from your if statement: if c=1, x = x + “,” + i

It looks like you are concatenating the “,” to each x value here.

The issue is in your for loop when constructing the x string.
You’re including the comma in the first loop. If you have the page numbers in an array, you can just use pagesArray.join(‘,’). If you need to use your for loop, so long as you have a means of testing whether you’re on the first step of your loop this is pretty easy.


x="";
for(var i = 0, length = pages.length(); i<length; i++)
{
if(i) x += ",";
x+=pages[i];
}

Sorry I can’t give you a more specific answer, but without clear code examples (like your full for loop) it’s hard to tell exactly what is taking place.
Either way, I hope this helps!

Thanks everyone for your replies :slight_smile:

Arrays automatically add commas between items when you convert them to a string.
Array.toString

So instead of that code above, you just need:


var pages = [0, 3, 5, 6, 9];
var x = pages.toString();
// x is a string that equals "0,3,5,6,9"

If you need any other type of separator, you can join the array together with a customised string, for example, with a comma and a space


var pages = [0, 3, 5, 6, 9];
var x = pages.join(', ');
// x is a string that equals "0, 3, 5, 6, 9"