68

I’d like to know if standard JS provides a way of splitting a string straight into a set of variables during their initial declaration. For example in Perl I would use:

my ($a, $b, $c) = split '-', $str;

In Firefox I can write

var [a, b, c] = str.split('-');

But this syntax is not part of the ECMAScript 5th edition and as such breaks in all other browsers. What I’m trying to do is avoid having to write:

var array = str.split('-');
var a = array[0];
var b = array[1];
var c = array[2];

Because for the code that I’m writing at the moment such a method would be a real pain, I’m creating 20 variables from 7 different splits and don’t want to have to use such a verbose method.

Does anyone know of an elegant way to do this?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
nb5
  • 683
  • 1
  • 5
  • 4
  • 2
    why do you need to dump these into `var` objects? What's the end game here? – hunter Aug 19 '10 at 13:51
  • It's part of a web form used to administrate a small database of on site events at our campus. In order to show users how their data is going to look once it's been formatted we take the information straight from the form fields (using jquery) and produce a small bit of HTML. In order to correctly format the date ranges and a few other bits of information it's much more convenient to have it stored in named variables rather than try to tease out the right values using something like $('input[name=start_date]').val().split(' '). See http://pastie.org/1102123 – nb5 Aug 19 '10 at 13:56
  • possible duplicate of [Unpacking array into separate variables in JavaScript](http://stackoverflow.com/questions/3422458/unpacking-array-into-separate-variables-in-javascript) – Andy E Aug 19 '10 at 13:59

4 Answers4

125

You can only do it slightly more elegantly by omitting the var keyword for each variable and separating the expressions by commas:

var array = str.split('-'),
    a = array[0], b = array[1], c = array[2];

ES6 standardises destructuring assignment, which allows you to do what Firefox has supported for quite a while now:

var [a, b, c] = str.split('-');

You can check browser support using Kangax's compatibility table.

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 3
    I suspected as much. Seems a damn shame to have to be so verbose about it. Ah well, thanks for your help :) – nb5 Aug 19 '10 at 14:03
  • You can also remove the "var" for golf code : [a,b,c]=str.split('-'); – Elo Apr 14 '17 at 07:20
  • Internet Explorer strikes again! – Akin Williams Jul 29 '19 at 23:22
  • 1
    This table shows destructuring assignment specifically: https://caniuse.com/mdn-javascript_operators_destructuring TL;DR supported everywhere except MSIE11 and older. – Luc Mar 20 '21 at 13:43
9
var str = '123',
    array = str.split('');

(function(a, b, c) {
    a; // 1
    b; // 2
    c; // 3
}).apply(null, array)
viam0Zah
  • 25,949
  • 8
  • 77
  • 100
  • apply is a cool method but I'm looking to use less code rather than more ;) – nb5 Aug 19 '10 at 14:12
  • @nb5: I don't think it's *that* much more code than `var a = array[0], b = array[1], c = array[2];`. – viam0Zah Aug 19 '10 at 14:21
  • perhaps but in this script I'd be using this 7 times. – nb5 Aug 19 '10 at 14:30
  • @mplungjain: It should work. You have to deal with the variables to see their values, e.g. try to `alert` them. – viam0Zah Aug 19 '10 at 14:31
  • 1
    +1 from me. The one difference between this and the comma-separated var solution is that these variables are available only within the scope of this function, rather than the outer scope too. That's not a problem if this closure is wrapped around the entire code that uses the variables. – Andy E Aug 19 '10 at 14:44
6

Split a string into two part variables for a 3 or more word sentence.

> var [firstName, lastName] = 'Ravindra Kumar Padhi'.split(/(\w+)$/)

> console.log({firstName: firstName.trim(), lastName: lastName.trim()})
{ firstName: 'Ravindra Kumar', lastName: 'Padhi' }
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
abhisekp
  • 4,648
  • 2
  • 30
  • 37
0

You could create a function that will loop through the Array that's created by the str.split method and auto generate variables this way:

function autoGenerateVarFromArray(srcArray, varNamePrefix)
{
  var i = 0
  while(i < srcArray.length)
  {
    this[varNamePrefix +'_' + i] = srcArray[i]; 
    i++;
  } 
}

Here's an example of how to use this:

var someString = "Mary had a little Lamb";
autoGenerateVarFromArray(someString.split(' '), 'temp');

alert(this.temp_3); // little
Gary
  • 1,001
  • 8
  • 17
  • This pretty cool but as far as I can see autogenerated variables using a single name prefix followed by a number would be little different from just directly referencing the array item by index. – nb5 Aug 19 '10 at 14:16
  • @nb5: That's true. This solution might be more scalable if you have a huge array and a lot of variables to initialize. If you just have a small array size then the other solutions posted are not so bad (var apple = a[1], banana = a[2], etc.) – Gary Aug 19 '10 at 14:48