How to split and assign 2 words?

I have a phrase with two words:

var phrase = "hello world" 

and I want to split and assign as in:

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

Is there an easier way than these three lines?

[updated]

I am looking for a way to do this in one line, for example:

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

Is it possible?

+8
javascript string split
source share
6 answers

If you are using Javascript 1.7 (and not just ECMAscript), you can use the destruction destination :

 var [a, b] = "hello world".split(" "); 
+9
source share

I'm not a JavaScript expert, but looking at your code, I would say that you can make it more efficient.

Your code calls break twice, which means the original string needs to be parsed twice. Although this may not be a big problem, this kind of programming is being added.

Thus, it would be more efficient to do the code as follows:

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

The only thing I do is that you cache the split result, not recount it.

 var phrase = "hello world"; var splitPhrase = phrase.split(" "); var word1 = splitPhrase[0]; var word2 = splitPhrase[1]; 
+2
source share
 var words = "hello world".split(" "); var word1 = words[0]; var word2 = words[1]; 

It is just as long, but much more readable. To answer your question, I think the above is easy enough without getting into a regular expression.

Update

JavaScript, unfortunately, does not have concurrent functions like Ruby. I.e

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

Instead, it will install both word1 and word2 in the returned array ["hello", "world"].

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

+2
source share

Late to the side, but here is the 1-line design that I used

 var word1, word2; (function(_){ word1 = _[0]; word2 = _[1]; })(phrase.split(" ")); 
+2
source share

Not sure if you can do this in "less lines", but you certainly don't need to split twice.

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

All Articles