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.
/[^\,]+/splits on one or more characters that are not a comma. Thus, JavaScript will split your string onred,blueetc. 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 getundefined(as with any array).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 meanssomeArray.join()is called, which by default puts commas in between. So you get commas joined by commas, resulting in even more commas.