JavaScript Practice Object Basics in JavaScript Practicing Object Basics Adding a Method Solution

split()

From my understanding the split(" ") adds space in between the words and splits it into an array like eg: ["Programming ", "with ","Treehouse " , "is " , "fun! "]. So shouldnt the space be counted as a character?

I should have provided a link. Most of that is from here

Updated function with no separator

function myFunction() {
  var str = "Programming with Treehouse is fun!";
  var res = str.split();
  return res
}

will return the whole string as a single element array

["Programming with Treehouse is fun!"]

Thanks

1 Answer

The syntax is:

string.split(separator, limit)

both parameters are optional

separator: Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item)

limit: An integer that specifies the number of splits, items after the split limit will not be included in the array

So :

function myFunction() {
  var str = "Programming with Treehouse is fun!";
  var res = str.split(" ");
  return res
}

splits on a space and returns

["Programming", "with", "Treehouse", "is", "fun!"]

nothing is added by the separator

I didnt get this part "separator: Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item)" an array with only one item?

mersadajan
mersadajan
21,274 Points

John Cannon the separator defines by what the substring (or in this case words) are separated by. In our sentence, we have words that are separated by a space " " , that is why we hand the split function a space in string format (" "). It will split the string at every space in the string and you will get an array of substrings, the words.