Reputation: 755
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 apple a day keeps", it should return "An --- a day keeps"
How can I do it?
Upvotes: 1
Views: 1797
Reputation: 154818
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/.
Upvotes: 3
Reputation: 9437
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");
Upvotes: 1