简体   繁体   English

删除所有出现的单词

[英]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/ 这是一个小提琴: 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". 在您的代码中, words[i]不会被解释为javascript语言,而是被解释为正则表达式语言,并且只会匹配“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. 我添加了\\b字边界,以确保删除的单词不是单词的一部分。

If you want to match the leading "This" you will also need to add the case-insensitive flag i : 如果你想匹配前导“This”,你还需要添加不区分大小写的标志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 : 在ES6中:

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

before ES6 : 在ES6之前:

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

You can create RegExp with constructor: 您可以使用构造函数创建RegExp

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

you can also check word boundaries as suggested by @Aaron and ignore case 你也可以检查@Aaron建议的单词边界并忽略大小写

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

Because you are replacing the actual text words[i] with nothing. 因为你正在用任何东西替换实际的文字words[i] Instead, you need to use the text to generate a regular expression. 相反,您需要使用该文本生成正则表达式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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