javascript split() array contains

Posted by Mahesha999 on Stack Overflow See other posts from Stack Overflow or by Mahesha999
Published on 2012-10-13T21:20:57Z Indexed on 2012/10/13 21:37 UTC
Read the original article Hit count: 222

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about regex