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
  • 22,420
  • 27
  • 75
  • 108

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
  • 139,281
  • 83
  • 327
  • 490
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
  • 70,983
  • 9
  • 108
  • 145