10

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?

Ben
  • 51,770
  • 36
  • 127
  • 149
The Student
  • 27,520
  • 68
  • 161
  • 264

6 Answers6

19

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

var [a, b] = "hello world".split(" ");
Ken
  • 516
  • 1
  • 5
  • 11
  • McStretch: It's available in any runtime that implements Javascript 1.7. I tested it in Rhino. – Ken Mar 30 '11 at 19:35
3
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.

McStretch
  • 20,495
  • 2
  • 35
  • 40
2

Late to the party, but here is a 1-line construct that I've used

var word1, word2;
(function(_){ word1 = _[0]; word2 = _[1]; })(phrase.split(" "));
Lucas
  • 8,035
  • 2
  • 32
  • 45
  • It doesn't make it a one-liner by just removing the new lines. :-P – Mattias Buelens Jan 26 '13 at 12:35
  • True, but I was going for a "mutivalue return" style in Javascript and this is as close as I got. I read it as, `[word1, word2] = phrase.split()`. See, one line. ;-) – Lucas Jan 28 '13 at 15:15
2

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

Your code calls split twice, which means the original string must be parsed twice. While that may not be a big deal, this kind of programming adds up.

So it would generally be more efficient to do code like this:

var words = phrase.split(" ");
var word1 = words[0];
var word2 = words[1];
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
2

The only suggestion I make is that you cache the result of the split, rather than recalculating it.

var phrase = "hello world";
var splitPhrase = phrase.split(" ");
var word1 = splitPhrase[0];
var word2 = splitPhrase[1];
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
1

Not sure you can do it in "less lines" but you certainly don't need to do the split twice.

 var words = "hello world".split(" "),
     word1 = words[0],
     word2 = words[1];
SavoryBytes
  • 35,571
  • 4
  • 52
  • 61