JavaScript 用于匹配字符串化数组中不包含搜索词的项目的正则表达式

JavaScript regex to match items in a stringified array that don't contain a search term

我想从字符串化数组中删除所有不包含字符串 'foo' 的跨度项。字符串如下所示:

["<span>This is some text</span>","<span>This is more foo</span>","
<span><span>Inner span blah</span>This is one has an inner span
 foo</span>","<span>Last one</span>"]

最终结果字符串应如下所示:

["<span>This is more foo</span>","<span><span>Inner span blah</span>
This is one has an inner span foo</span>"]

使用 JSON.parse() 创建一个数组,然后进行过滤,但对于我的目的来说速度不够快。

我已经尝试过具有负前瞻性的正则表达式变体,但似乎无法使它们起作用。

你可以尝试类似的东西。

var array = ["<span>This is some text</span>","<span>This is more foo</span>","
<span><span>Inner span blah</span>This is one has an inner span
 foo</span>","<span>Last one</span>"];

for (var item in array) {
  var value = array[item];
  if(value.indexOf('foo') < 0) {
    array.splice(item, 1)
  }
}

解释:
首先,您使用所有字符串初始化 array
使用 for in 循环遍历该数组。
每次找到单词 foo 时,都会从数组中删除当前元素。

JavaScript提供函数实现你想要的,使用正则表达式将节省不必要的资源。

代码:

var myArray = ["<span>This is some text</span>","<span>This is more foo</span>","<span><span>Inner span blah</span>This is one has an inner span foo</span>","<span>Last one</span>"];

for (i=0;i<myArray.length;++i) {
  if(myArray[i].indexOf("foo") === -1){
    myArray.splice([i], 1);
  }
};
console.log(myArray);

输出:

["<span>This is more foo</span>", "<span><span>Inner span b...n inner span foo</span>"]

CODEPEN DEMO

解释:

循环myArray:

for (i=0;i<myArray.length;++i)

使用 indexOf 检查 foo 是否存在

if(myArray[i].indexOf("foo") === -1)

如果 foo 不存在,使用 splice

将其从数组中删除
myArray.splice([i], 1);