September 18, 2000 - Exploding a String

Yehuda Shiran September 18, 2000
Exploding a String
Tips: September 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Probably, there are many times when you want to create an array from a simple string of values. This simple function can take in a string and a delimiter (which can be anything you like) and it returns an array of those values.

function explodeArray(item,delimiter) {
  tempArray=new Array(1);
  var Count=0;
  var tempString=new String(item);
  while (tempString.indexOf(delimiter)>0) {
    tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
    tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1); 
    Count=Count+1
  }
  tempArray[Count]=tempString;
  return tempArray;
}

We first copy the parameter item to tempString:

var tempString=new String(item);

We then loop over all delimiters, and on each iteration we take the first delimited string as the next array element:

tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));

and then extracting the rest of the string to tempString:

tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1); 

It simply starts just after the delimiter and ends at the last index of the array. Notice the difference between substring() and substr(). The first method expects to receive an index, while the other method expects to get the substring length.

Let's take an example using this function. A string could look like this:

tempString="One;Two;Three;Four;Five";

We then take the function and use it like this:

tempArray=explodeArray(tempString,";");

And it returns an array that looks like this:

tempArray[0]="One"
tempArray[1]="Two"
tempArray[2]="Three"
tempArray[3]="Four"
tempArray[4]="Five"

Its quick and easy, and you may find many uses for it.

This tip has been contributed by Chris Motch.