我有一个数组如下:
var arr = ["apple", "banana", "carrot"];
我想替换所有具有类似于数组
的单词的句子function replaceString(fruits){
return fruits.replace(arr, "---");
}
所以,如果我传递一个字符串 - “每天一个苹果保持”,它应该返回“An --- a day keeps”
我该怎么做?
答案 0 :(得分:3)
在这种情况下使用正则表达式,例如
"I like apples but I prefer carrots.".replace(/apple|banana|carrot/g, "---");
// I like ---s but I prefer ---s.
修改:这可能更适合您:
"Apple and bananasauce are my favourites, but I hate carrot and other variations of carrot."
.replace(/(\b)(apple|banana|carrot)(\b)/gi, "$1---$3");
如果你真的想要一个数组,试试这个:
var regexp = new RegExp("(\\b)("+arr.join("|")+")[s]?(\\b)", "gi");
"Apple and bananasauce are my favourites, but I hate carrots and other variations of carrot."
.replace(regexp, "$1---$3");
答案 1 :(得分:1)
您可以将replace
方法与正则表达式一起使用,添加非单词字符以完全匹配这些单词:
fruits.replace(/(\W?)(apple|banana|carrot)(s?)(\s|\W|$)/ig, "$1---$3$4");