tags:

views:

4916

answers:

2

Hi everybody...

I'm just curious how I go about splitting a variable into a few other variables.

For example, say I have the following javascript:

var coolVar = '123-abc-itchy-knee';

And I wanted to split that into 4 variables, how does one do that?

I know how to do something of the sort in php... but javascript.. I'm a newbie.

To wind up with an array where

array[0] == 123

and

array[1] == abc

etc would be cool...

Or (a variable for each part of the string)

var1 == 123  
and 
var2 == abc

Could work... either way. How do you split a javascript string?

+3  A: 

Use split on string:

var array = coolVar.split(/-/);
Sinan Taifour
Does split take regexes? I thought it just took a search string.
Macha
It can take /-/ as well.
Amber
It doesn't even have to be a constant regex, it can be more complex. For example: `"hello-there_stranger".split(/-|_/)` returns a 3-element array.
Sinan Taifour
+15  A: 

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc
Amber
that is so simpler than i thought it was.... thanks Dav
cosmicbdog