Reputation: 9
First I have an array that has two strings in it.
var Array = ["firstName lastName" , "anotherString"]
I would like to create a function that takes in a string as a parameter and returns an array by breaking up the input string into individual words. So the output in this example would be ["firstName", "lastName"] ?
I know it would look something like this
var newFun = function(string) {
return string[0] // than do something else
}
Help is greatly appreciated!
Upvotes: 0
Views: 18690
Reputation: 242
This splitter will take any array with mixed string (strings with spaces and without spaces) and split them in a linear array.
var splitter = (array) => {
return array.reduce((acc, value) => {
return /\s/.test(value) ? acc.concat(value.trim().split(' ')) : acc.concat(value) ;
}, []);
}
console.log(splitter(["There is proper space", "ThereIsNoSpace"]));
will output:
['There', 'is', 'proper', 'space', 'thereisnospace']
Upvotes: 0
Reputation: 4271
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/
Upvotes: 2
Reputation: 51201
Several comments on your code:
1) the function you are looking for is String.prototype.split
:
var string = "firstName lastName";
string.split(" ");
// returns an array: ["firstName","lastName"]
2) don't call your array Array
. This is a "reserved word"* for the Array prototype! You are overwriting the prototype, if you do so!
3) Keep the naming of your parameters consistent. This way you avoid error like you did in your code. Handing over an array and call the parameter string is a bad idea. string[0]
returns the first symbol of the string, array[0]
the first element of your array. Also, name the function appropriately.
Your code should look like this:
var array = ["firstName lastName" , "anotherString"];
function returnSplitString(string){
return string.split(" ");
}
var splitStringArray = returnSplitString(array[0]);
*
In the strict technical sense it is not, because you CAN name your variable that way, however it's a bad idea to do so.
Upvotes: 0
Reputation: 51
You can use the string split method:
function splitString(input) {
return input.split(" ");
}
Upvotes: 0
Reputation: 1874
You could do something like this using the split method from the object String
var newFun = function(string) {
return string[0].split(" ");
}
Voilà !
Upvotes: 0
Reputation: 81
The index of [0] is actually the first character of the string.
Do this:
var myString = "My Name";
var splitResult = myString.split(" ");
Will result in:
["My", "Name"]
Upvotes: 1