43

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?

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?

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
willdanceforfun
  • 11,044
  • 31
  • 82
  • 122

3 Answers3

94

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
  • 507,862
  • 82
  • 626
  • 550
19

Use split on string:

var array = coolVar.split(/-/);
Sinan Taifour
  • 10,521
  • 3
  • 33
  • 30
  • 2
    Does split take regexes? I thought it just took a search string. – Macha Aug 01 '09 at 12:18
  • 9
    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 Aug 01 '09 at 12:24
3

as amber and sinan have noted above, the javascritp '.split' method will work just fine. Just pass it the string separator(-) and the string that you intend to split('123-abc-itchy-knee') and it will do the rest.

    var coolVar = '123-abc-itchy-knee';
    var coolVarParts = coolVar.split('-'); // this is an array containing the items

    var1=coolVarParts[0]; //this will retrieve 123

To access each item from the array just use the respective index(indices start at zero).

Shadrack Orina
  • 7,713
  • 2
  • 31
  • 36