Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split and assign 2 words?

I have phrase with two words:

var phrase = "hello world"

and I want to split and assign like in:

var words = phrase.split(" ");
var word1 = words[0];
var word2 = words[1];

Is there a easier way than this three lines?

[updated]

I looking to a way for do it in a single line, like:

var word1 word2 = phrase.split(" ");

is it possible?

like image 981
The Student Avatar asked Mar 30 '11 17:03

The Student


2 Answers

If you're using Javascript 1.7 (not just ECMAscript), you can use destructuring assignment:

var [a, b] = "hello world".split(" ");
like image 161
Ken Avatar answered Oct 23 '22 10:10

Ken


var words = "hello world".split(" ");
var word1 = words[0];
var word2 = words[1];

Is just as long, but much more readable. To answer your question, I think the above is easy enough without getting into regex.

Update

JavaScript unfortunately does not have parallel assignment functionality like Ruby. That is,

var word1, word2 = phrase.split(" "); will not set word1 and word2 to words[0] and words[1] respectively.

Instead it would set both word1 and word2 to the returned array ["hello", "world"].

Now you could use the returned array instead of explicitly setting the results into variables and access them by index. This is especially useful to avoid creating a large number of variables when the string is quite long.

like image 3
McStretch Avatar answered Oct 23 '22 11:10

McStretch