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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

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.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint