4

Possible Duplicate:
Possible to assign to multiple variables from an array?

If in python i can do this

x = "Hi there and hello there"
v1, v2, v3, v4, v5 = x.split(" ")

but im not sure how to do it in javascript..

Community
  • 1
  • 1
Natsume
  • 881
  • 3
  • 15
  • 22

5 Answers5

5

You can turn it into an array by using javascript .split

For example

x = "Hi there and hello there";
var array = x.split(" ");

Then all your variables will be in the array like below

array[0]
array[1]
array[2]

You can show this using console.log or an alert like so.

console.log(array[0]);
alert(array[0]);

References

http://www.tizag.com/javascriptT/javascript-string-split.php

Undefined
  • 11,234
  • 5
  • 37
  • 62
5

What you are asking is called "destructuring assignment" which is a feature of Javascript 1.7. Sadly, not all browsers support these JS 1.7 features (Chrome for example, executes code marked as JS 1.7 but does not yet support this feature).

Your code will work on Firefox (as long as you mark it as JS 1.7 and with a slight modification) but not on Chrome.

To see this in action, use the following with Firefox:

<script type="application/javascript;version=1.7"/>
    x = "Hi there and hello there"
    var [v1, v2, v3, v4, v5] = x.split(" ")
</script>
Tiago Espinha
  • 1,149
  • 1
  • 11
  • 19
  • This is neat and the way I was expecting splits to be done. (Having been using perl for a long time, I like this simple approach). Sadly firefox is the only thing that supports :( – Anshul Jul 18 '14 at 07:48
  • omg this works in Google Apps Script! You can even leave out the ones you don't need like this `var [, component, method] = arguments.callee.name.split('_');` – toddmo Dec 23 '19 at 19:09
1

split splits the string into an array of strings.

Jon Taylor
  • 7,865
  • 5
  • 30
  • 55
1

Split returns an array.

var x = "Hi there and hello there"
var v = x.split(" ")
console.log(v[0]);
console.log(v[1]);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

if you can attach the variables to an object, then you could do it this way:

var stringToWords = function (str) {
if (typeof str === "string") {
    var stringsArray = str.split(" "),
        stringsSet = {};

    for (var i = 0, wordsNumber = stringsArray.length; i < wordsNumber; i++) {
        stringsSet['str' + (i + 1)] = stringsArray[i];
    }

    return stringsSet;
} else { 
    return str + " is not a string!!!"}

};

// this will return an object with required strings

var allStringWords = stringToWords("Hi there and hello there");

//then you can access a word this way:

allStringWords.str1

but I'm sure there are shorter ways to gain the same