tgo*_*gos 1 javascript regex variables stop-words
我想从文本中删除停用词,但无法正确使用正则表达式和变量.例如,我删除了停用词"he",但这也会影响单词"when".我尝试使用这样的单词边界:
new RegExp('\b'+stopwords[i]+'\b' , 'g') 但不起作用......
在这里看一个小例子:jsFiddle
var stopwords = ['as', 'at', 'he', 'the', 'was'];
for (i = 0; i < stopwords.length; i++) {
str = str.replace(new RegExp(stopwords[i], 'g'), '');
}
Run Code Online (Sandbox Code Playgroud)
也许这样的事情
str = str.replace(new RegExp('\\b('+stopwords.join('|')+')\\b', 'g'), '');
Run Code Online (Sandbox Code Playgroud)
你必须在RegExp中双重转义,你可以加入所有创建
/\b(as|at|he|the|was)\b/g
Run Code Online (Sandbox Code Playgroud)