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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business