Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string straight into variables

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?

like image 668
nb5 Avatar asked Aug 19 '10 13:08

nb5


People also ask

How do I split a string into separate variables?

Use the Split() Function to Split a String Into Separate Variables in PowerShell. The Split() is a built-in function used to split a string in PowerShell. We can store the result of the Split() function into multiple variables.

How do you split a string into multiple variables in Python?

Unpack the values to split a string into multiple variables, e.g. a, b = my_str. split(' ') . The str. split() method will split the string into a list of strings, which can be assigned to variables in a single declaration.

How do I split a string into string?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.

How do I split a string into an object?

Description. In JavaScript, split() is a string method that is used to split a string into an array of strings using a specified delimiter. Because the split() method is a method of the String object, it must be invoked through a particular instance of the String class.


2 Answers

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.

like image 128
Andy E Avatar answered Sep 28 '22 10:09

Andy E


var str = '123',     array = str.split('');  (function(a, b, c) {     a; // 1     b; // 2     c; // 3 }).apply(null, array) 
like image 34
viam0Zah Avatar answered Sep 28 '22 09:09

viam0Zah