【发布时间】:2018-04-04 15:37:31
【问题描述】:
使用 Javascript。 (注意有一个类似的post,但 OP 请求 Java,这是用于 Javascript 的)
我正在尝试从整个字符串中删除单词列表而不进行循环(最好使用正则表达式)。
这是我目前所拥有的,它删除了一些单词,但不是全部。有人可以帮助确定我在使用 RegEx 函数时做错了什么吗?
//Remove all instances of the words in the array
var removeUselessWords = function(txt) {
var uselessWordsArray =
[
"a", "at", "be", "can", "cant", "could", "couldnt",
"do", "does", "how", "i", "in", "is", "many", "much", "of",
"on", "or", "should", "shouldnt", "so", "such", "the",
"them", "they", "to", "us", "we", "what", "who", "why",
"with", "wont", "would", "wouldnt", "you"
];
var expStr = uselessWordsArray.join(" | ");
return txt.replace(new RegExp(expStr, 'gi'), ' ');
}
var str = "The person is going on a walk in the park. The person told us to do what we need to do in the park";
console.log(removeUselessWords(str));
//The result should be: "person going walk park. person told need park."
【问题讨论】:
-
首先去掉
|周围的空白。 -
如果我这样做,那么该函数会删除所有字符而不是单词。 (即:“walk”将是“wlk”)
-
@Jared Smith,我收回我上面的声明,因为 RomanPerekhrest 使用了你的评论。
标签: javascript regex string