2

While learning JavaScript, I did not get why the output when we print the array returned of the Sting.split() method (with regular expression as an argument) is as explained below.

var colorString = "red,blue,green,yellow";
var colors = colorString.split(/[^\,]+/);
document.write(colors); //this print 7 times comma: ,,,,,,,

However when I print individual element of the array colors, it prints an empty string, three commas and an empty string:

 document.write(colors[0]);  //empty string
 document.write(colors[1]);  //,
 document.write(colors[2]);  //,
 document.write(colors[3]);  //,
 document.write(colors[4]);  //empty string
 document.write(colors[5]);  //undefined
 document.write(colors[6]);  //undefined

Then, why printing the array directly gives seven commas.

Though I think its correct to have three commas in the second output, I did not get why there is a starting (at index 0) and ending empty string (at index 4).

Please explain I am screwed up here.

3 Answers 3

8

/[^\,]+/ splits on one or more characters that are not a comma. Thus, JavaScript will split your string on red, blue etc. The resulting leftovers, then, are the empty string at the beginning (the substring from index 0 to 0), the commas, and the empty string at the end. If you go out of bounds of the array you get undefined (as with any array).

red,blue,green,yellow
xxx xxxx xxxxx xxxxxx   <-- x is what is being eaten during split, because it's the delimiter

You just want .split(","), which splits on commas, so that the commas are eaten and you are left with the colors.

Now, when you do document.write(someArray), the array is converted into a string so that it can be displayed. This effectively means someArray.join() is called, which by default puts commas in between. So you get commas joined by commas, resulting in even more commas.

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

Comments

5

When you print out the array, the different elements of the array are also separated by commas. So your output are these 5 array elements:

[empty string],[comma],[comma],[comma],[empty string]

Amounting to 7 commas. The reason why you get commas and empty strings instead of colors is, that split will split at everything that matches (instead of giving you back everything that matches). So simply don't use regular expressions at all, but just split at ,:

var colors = colorString.split(',');

Comments

2

[^\,] <- this means anything BUT commas.

try var colors = colorString.split(',');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.