0

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!

4
  • Array[0].split(" ") ? Commented Dec 11, 2014 at 20:03
  • "I would like to create a function that..." — and you got stuck, where? Commented Dec 11, 2014 at 20:04
  • Spending a little time learning Javascript will pay off in spades! Commented Dec 11, 2014 at 20:05
  • You should never use Array as a variable name. Just saying. Commented Dec 11, 2014 at 20:06

7 Answers 7

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Not to mention that it's a bad idea to call a variable Array and hand an array to a function and call the parameter string...
string is no reserved word, String however is;) (Technically it is not, because you CAN use this word as variable name, this however will break some funcitonality)
1

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"]

Comments

0

You could do something like this using the split method from the object String

var newFun = function(string) {
     return string[0].split(" ");
}

Voilà !

1 Comment

Indeed. The split function will return an array of string splitted according to the character passed in parameter. So if I have a string "I really love apple"and split it using the space character myStr.split(" ") it will returns this ["I", "really", "love", "apple"]
0

You can use the string split method:

function splitString(input) {
    return input.split(" ");
}

Comments

0

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.

Comments

0
var newFun = function(str) {
 return str.split(" "); 

}

Comments

0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.