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..
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..
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
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>
Split returns an array.
var x = "Hi there and hello there"
var v = x.split(" ")
console.log(v[0]);
console.log(v[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