choping up a text string?

Josh Simpson's picture

They have: 147 posts

Joined: Dec 1999

Im learning to use javascript at the moment
and have had a little trouble
in my page i have this

var text_sting=('winamp_ra_28k")

how do i cut up the string at the underscores so i have three different var's
eg
var1 = winamp
var2 = ra
var3 = 28k

?

JLS (Joshua Lee Simpson)

They have: 99 posts

Joined: May 1999

Use the .index, .length, and .substring functions

text_string = new String("winamp_ra_28k");

//search for position of first _
temp = text_string.indexOf("_");
//search for position of next underscore
temp2= text_string.indexOf("_",temp+1);

//assign first string from start to temp(non-inclusive)
first_string=text_string.substring(0,temp);
//assign second string from temp+1 to temp2(non-inclusive)
second_string=text_string.substring(temp+1,temp2);
//assign third string from temp2+1 to end of string
third_string=text_string.substring(temp2+1,text_string.length);

[Edited by tazman on 07-16-2000 at 01:32 AM]

They have: 231 posts

Joined: Feb 2000

Alternatively you can use the split() method which was introduced into IE4 and NN4.

var textStr = "winamp_ra_28k";

This creates a new array with three separate entries:

var txtStrArray = textStr.split("_");

If you want to store them into three separate variables:

var textStr1 = txtStrArray[0];
var textStr2 = txtStrArray[1];
var textStr3 = txtStrArray[2];

:: Lloyd Hassell :: http://www14.brinkster.com/lloydh ::

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.