我正在尝试使用正则表达式构建查找和删除类型功能。我能够达到可以删除字符串的地步,但发现无法删除带有字符的字符串。当使用普通字符串(如 var word = "is"
)时,它似乎工作正常,直到遇到 .
,然后我得到奇怪的不需要的输出。
例如,当将字符合并到我想删除的字符串中时,还会出现一些其他不需要的事件(请注意 var word = "is."
而不是 is
下面的代码:
var myarray = ["Dr. this is", "this is. iss", "Is this IS"]
var my2array = []
var word = "is."
//var regex = new RegExp(`\\b${word}\\b`, 'gi');
var regex = new RegExp('\\b' + word + '\\b', 'gi');
for (const i of myarray) {
var x = i.replace(regex, "")
my2array.push(x)
}
myarray = my2array
console.log(myarray)
["Dr. this is", "this is.", "this IS"]
这个 ^ 在几个方面是错误的(由于某种原因 iss
消失了, is.
仍然存在 - 这是我试图删除的主要字符串,第一个 is
在最后一个索引中消失了...)
即在这种情况下,我想要的输出是 ["Dr. this is", "this iss", "Is this IS"]
我也尝试过使用模板字面量,这在我注释掉的代码中可以看出。
目标是简单地从我的数组中删除 var word
中的任何值。该值是常规字符串、带字符的字符串还是仅包含字符。 (当然在我休息的框架内)。
最佳答案
正则表达式方法有几个问题:
-
.
是特殊的正则表达式字符,需要在您的单词中进行转义 - 字边界
\b
.
之后不会匹配
您可以使用这个基于正则表达式的解决方案:
var myarray = ["Dr. this is", "this is. iss", "Is this IS"]
var my2array = []
var word = "is."
// using lookahead and lookbehind instead of word boundary
var regex = new RegExp('\\s*(?<!\\S)' +
word.replace(/\W/g, "\\$&") + '(?!\\S)\\s*')
for (const i of myarray) {
var x = i.replace(regex, " ")
my2array.push(x)
}
myarray = my2array
console.log(myarray)
-
.replace(/\W/g, "\\$&")
将转义给定的所有非单词字符 词。 -
(?<!\S)
断言前一个字符不是非空格字符的否定回顾 -
(?!\S)
断言下一个字符不是非空格字符的否定回顾
关于javascript - 从 Javascript 数组中删除带有字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976067/