Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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?

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.