Javascript - Converting a String to an Array

Introduction

A string can be converted to an array with the split() method:

Demo

var str = "a,b,c,d,e,f";
var arr = str.split(",");
console.log(arr[0]);//from  w w w .j a va 2  s .c  o m

//separator is omitted,
arr = str.split();
console.log(arr[0]);

Result

If the separator is omitted, the returned array will contain the whole string in index [0].

If the separator is "", the returned array will be an array of single characters:

Demo

var str = "Hello";
var arr = str.split("");
var text = "";
var i;//from   w  w w .j a va 2  s.  co  m
for (i = 0; i < arr.length; i++) {
    text += arr[i] + "\n"
}
console.log(text);

Result

Related Topic