javascript - 从 Javascript 数组中删除带有字符的字符串

标签 javascript arrays regex

我正在尝试使用正则表达式构建查找和删除类型功能。我能够达到可以删除字符串的地步,但发现无法删除带有字符的字符串。当使用普通字符串(如 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 中的任何值。该值是常规字符串、带字符的字符串还是仅包含字符。 (当然在我休息的框架内)。

最佳答案

正则表达式方法有几个问题:

  1. .是特殊的正则表达式字符,需要在您的单词中进行转义
  2. 字边界 \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/

相关文章:

javascript - 当我使用 bootstrap 4 时,为什么粘性 header 在表单标签中不起作用?

单撇号之间的Python正则表达式findall()子串

javascript - 在 JavaScript 中将最低有效数字移出十六进制序列

javascript - 组合两个元素数量不同的数组

javascript - 如何删除引号或将此字符串作为普通数组传递

c++ - 在c++中设置嵌套数组

python - Re.match 在 python 中总是返回 None

python - 如何执行单个替换,然后使用正则表达式捕获?

javascript - 在 Javascript 中实现后退按钮 'Warning' 以便在 Flex 中使用

javascript - 从数组中的时间间隔计算唯一时间