Splitting a String into an Array

The split() method can be used to splits a string into an array of strings, using the syntax str.split(separator, limit). The seperator argument specifies the string at which each split should occur, whereas the limit arguments specifies the maximum length of the array.

If separator argument is omitted or not found in the specified string, the entire string is assigned to the first element of the array. The following example shows how it works:

var fruitsStr = "Apple, Banana, Mango, Orange, Papaya";
var fruitsArr = fruitsStr.split(", ");
document.write(fruitsArr[0]); // Prints: Apple
document.write(fruitsArr[2]); // Prints: Mango
document.write(fruitsArr[fruitsArr.length - 1]); // Prints: Papaya
// Loop through all the elements of the fruits array 
for(var i in fruitsArr) {  
    document.write("<p>" + fruitsArr[i] + "</p>");

To split a string into an array of characters, specify an empty string ("") as a separator.

var str = "INTERSTELLAR";
var strArr = str.split("");
document.write(strArr[0]); // Prints: I
document.write(strArr[1]); // Prints: N
document.write(strArr[strArr.length - 1]); // Prints: R
// Loop through all the elements of the characters array and print them
for(var i in strArr) {  
    document.write("<br>" + strArr[i]);