Evgenij Reznik
Evgenij Reznik

Reputation: 18594

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/

Upvotes: 3

Views: 306

Answers (3)

Aaron
Aaron

Reputation: 24802

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(" ");

Upvotes: 5

madox2
madox2

Reputation: 51841

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")

Upvotes: 2

CharlesLeaf
CharlesLeaf

Reputation: 3201

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"), "")

Upvotes: 1

Related Questions