JavaScript: How to Explode a String into an Array Programming 13 FEB 2012

Coming from PHP, I’m well versed in using the handy explode function to force a string into an array, using a specified delimiter character to chop up the string into the little bits that are to be stored in the array.

Happily for me, plain old vanilla JavaScript also has this ability built into the language, choosing to call its version of this functionality “split”.

From the official definition: The split() method is used to split a string into an array of substrings, returning the new array containing the substrings.

It accepts two parameters, namely the separator and the limit, both of which are actually optional by the way. The separator parameter is where you specify the delimiter character (if you omit this, the entire string will be stuffed into a single element array ). The optional limit parameter if set will control the number of splits.

A few examples on using split:

var str="How are you doing today?";

//some split usage examples
document.write(str.split() + "<br />");
document.write(str.split(" ") + "<br />");
document.write(str.split("") + "<br />");
document.write(str.split(" ",3));

//the output (',' indicates array boundary)
//How are you doing today?
//How,are,you,doing,today?
//H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
//How,are,you 

Useful.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.