Replace words in a string
I have an array as follows:
var arr = ["apple", "banana", "carrot"];
I want to replace all sentences which have the words similar to the array
function replaceString(fruits){
return fruits.replace(arr, "---");
}
So if I pass a string - "An appl开发者_开发百科e a day keeps", it should return "An --- a day keeps"
How can I do it?
Use a regular expression in this case, e.g.
"I like apples but I prefer carrots.".replace(/apple|banana|carrot/g, "---");
// I like ---s but I prefer ---s.
Edit: This might fit you better:
"Apple and bananasauce are my favourites, but I hate carrot and other variations of carrot."
.replace(/(\b)(apple|banana|carrot)(\b)/gi, "$1---$3");
If you really want an array, try this:
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");
Live example: http://jsfiddle.net/FaZSD/.
You can use the replace
method with a regular expression, adding non-word characters to match exactly those words:
fruits.replace(/(\W?)(apple|banana|carrot)(s?)(\s|\W|$)/ig, "$1---$3$4");
精彩评论