我有一个句子,我想从中删除一些词。
如果我有:
"jQuery is a Unique language"
和一个名为 garbageStrings 的数组:
var garbageStrings = ['of', 'the', "in", "on", "at", "to", "a", "is"];
我想去掉句子中的“is”和“a”。
但是如果我使用这个:/This statement is inside a for loop.我正在循环整个句子并在 garbageStrings/
中找到匹配项var regexp = new RegExp(garbageStrings[i]);
字符串将变成“jQuery Unique lnguge”
请注意,语言中的“a”已从句子中删除。
我没想到会这样。
最佳答案
像这样:
function keyword(s) {
var words = ['of', 'the', 'in', 'on', 'at', 'to', 'a', 'is'];
var re = new RegExp('\\b(' + words.join('|') + ')\\b', 'g');
return (s || '').replace(re, '').replace(/[ ]{2,}/, ' ');
}
关于javascript - RegExp : I want to remove unnecessary words in the Sentence. 我该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/861721/