How do I spilt a string in JavaScript by using a WORD as a delimiter? [closed]

流过昼夜 提交于 2019-12-24 10:38:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!