问题
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??
回答1:
… 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"]
回答2:
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
来源:https://stackoverflow.com/questions/12465610/how-do-i-spilt-a-string-in-javascript-by-using-a-word-as-a-delimiter