javascript - 忽略单词列表

标签 javascript regex variables replace

我有一个要忽略的单词列表。但是,当我调用它时,它会替换它的每个实例,即使它在字符串中也是如此。

例如:“he”最终将“the”变成了“t”。

我怎样才能让它只删除单独的单词?

代码如下:

var commonWords=/and|a|an|has|he|to|was|in|were|are|is|will|as|it|if|
with|at|its|it's|be|by|on|that|from|the|about|again|all|almost|also|although|
always|among|another|any|be|because|been|before|being|between|both|by|can|could|
did|do|does|doesn't|'|done|due|during|each|either|enough|from|had|has|have|having|
here|i|if|into|is|isn't|itself|just|may|might|most|mostly|must|nor|no|neither|nearly|
of|often|on|our|ours|his|hers|he's|he|she|she's|overall|perhaps|quite|rather|really|
regarding|seem|seems|seen|several|should|show|showewd|shown|shows|significant|
significantly|since|so|some|such|than|that|then|their|theirs|there's|therefore|these|
they|this|those|through|thus|to|upon|use|used|using|various|very|was|we|were|what|when|
which|while|with|within|without|would|however|or|for|the|but|etc|yet|/g;

commonWords.ignoreCase;

var w = w.replace(commonWords, '');

最佳答案

您不是要替换字符串中的任何实例,而是要替换整个单词。您需要查找 word boundaries使用 \b anchor 。

例如……

var commonWords = /\b(and|a|an|has|he|she)\b/g;

关于javascript - 忽略单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19965628/

相关文章:

JavaScript 父变量值不规则?

javascript - 你知道任何显示如何使用 Canvas 绘制思维导图的示例代码吗?

javascript - 使用自动增量 Javascript 在表中插入行

regex - 如何在正则表达式中获得负面前瞻以接受更多单词

regex - 用文字替换换行符\n

c# - 如何创建一个 "buffer"来存储每个帧的变量的先前值

javascript - 单击 <Link> 元素时路由器会复制

javascript - Vue 3 : Unable to update parent data from child component checkbox

javascript - 如何使用 JavaScript 替换字符串中除第一个和最后一个字符之外的所有字符

Javascript 有一个表单提交,只需更新 div 标签中的 html