简体   繁体   中英

Remove all occurrences of words

I'm trying to remove all occurrences of words in a text. The words are saved in an array.
But instead of removing them, I just get my original text back:

var text = "This is just a little test, to check if it works."
var words = ["this", "is", "a", "to", "if", "it"];

for (i = 0; i < words.length; i++) {
  text = text.replace(/words[i]/g, "")
}

alert(text); // result should be: just little test, check works.

Here is a fiddle: https://fiddle.jshell.net/y07qgooq/

In your code words[i] isn't interpreted as javascript language but as regex language, and will only match "wordsi". You can craft your regex in the following fashion :

new RegExp("\\b" + words[i] + "\\b", "g")

I added \\b word boundaries to make sure the removed words are not parts of words.

If you want to match the leading "This" you will also need to add the case-insensitive flag i :

new RegExp("\\b" + words[i] + "\\b", "gi")

If you did not have punctuation, it would be more efficient to use the following alternative :

in ES6 :

text.split(" ").filter(word => words.indexOf(word) == -1).join(" ");

before ES6 :

text.split(" ").filter(function(word) { return words.indexOf(word) == -1; }).join(" ");

You can create RegExp with constructor:

text = text.replace(new RegExp(words[i], "g"), "");

you can also check word boundaries as suggested by @Aaron and ignore case

new RegExp("\\b" + words[i] + "\\b ", "gi")

Because you are replacing the actual text words[i] with nothing. Instead, you need to use the text to generate a regular expression.

text = text.replace(new RegExp(words[i], "g"), "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM