1

Thanks for looking!

Using JavaScript, how do I split a string using a whole word as the delimiter? Example:

var myString = "Apples foo Bananas foo Grapes foo Oranges";
var myArray = myString.split(" foo ");

//myArray now equals ["Apples","Bananas","Grapes","Oranges"].

Thanks in advance.

UPDATE

Terribly sorry all, I had an unrelated error that was preventing this from working before. How do I close this question??

Community
  • 1
  • 1
Matt Cashatt
  • 23,490
  • 28
  • 78
  • 111

2 Answers2

7

… just like you've shown?

> "Apples foo Bananas foo Grapes foo Oranges".split(" foo ")
["Apples", "Bananas", "Grapes", "Oranges"]

You could also use a regular expression as the delimiter:

> "Apples foo Bananas foo Grapes foo Oranges".split(/ *foo */)
["Apples", "Bananas", "Grapes", "Oranges"]
David Wolever
  • 148,955
  • 89
  • 346
  • 502
3

If it can only be a delimiter if it's a full word (berries, but not blackberries), you can use word boundaries in a regular expression:

var arr = fruityString.split(/\bfoo\b/);

Note that dashes (-) are also considered word-boundaries, but you can adapt your expression so it doesn't split on dashes either: use the regex I provided here for that

Community
  • 1
  • 1
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149