So simple, use the String.prototype.split method to split strings into array list.
MDN:
The split() method splits a String object into an array of strings by separating the string into substrings.
return str.split(' ');
@Christoph:
You are using some very bad conventions here.
var Array
function (string)
Array is a predefined class in javascript and string is pretty close to the predefined class String, so just avoid using them completely.
var arr;
function (str)
Short Method: splits a string with multiple words, handles funky strings that String.prototype.split(' ') can't handle like " firstName Lastname" or just "firstName Lastname". returns an Array
function smartSplit (str) {
// .trim() remove spaces surround the word
// /\s+/ split multiple spaces not just one ' '
return str.trim().split(/\s+/);
}
Test Case:
// case: split(' ');
console.log(" firstName lastName".split(' '));
// result: ["", "", "", "firstName", "", "", "", "lastName"]
// case: split(/\s+/)
console.log(" firstName lastName".split(/\s+/));
// result: ["", "firstName", "lastName"]
// case: .trim().split(/\s+/)
console.log(smartSplit(" firstName lastName"));
// result: ["firstName", "lastName"]
Complete Method: same as smartSplit except for it expects an Array as a parameter instead of a String
function smartSplitAll (strArr) {
var newArr = [];
for (var i = 0; i < strArr.length; i++) {
// expecting string array
var str = strArr[i].trim();
// split the string if it has multiple words
if (str.indexOf(' ') > -1)
newArr = newArr.concat(str.split(/\s+/));
else
newArr.push(str);
}
return newArr;
}
console.log(smartSplitAll(["firstName lastName", "anotherString"]);
// result: ["firstName", "lastName", "anotherString"]
Code lives here: http://jsfiddle.net/8xgzkz16/
Array[0].split(" ")?Arrayas a variable name. Just saying.