Split a string straight into variables

JavascriptStringDestructuring

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

var str = '123',
    array = str.split('');

(function(a, b, c) {
    a; // 1
    b; // 2
    c; // 3
}).apply(null, array)

Solution 3 - Javascript

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' }

Solution 4 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionnb5View Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow
Solution 2 - Javascriptviam0ZahView Answer on Stackoverflow
Solution 3 - JavascriptabhisekpView Answer on Stackoverflow
Solution 4 - JavascriptGaryView Answer on Stackoverflow