jquery - 使用indexOf()搜索多个字符串并添加到数组

标签 jquery

我有以下工作代码。

indexMatches = [];
function getMatchIndexes(str, toMatch) {
    var toMatchLength = toMatch.length,
        match,
        i = 0;

    while ((match = str.indexOf(toMatch, i)) > -1) {
        indexMatches.push(toMatch);
        i = match + toMatchLength;
    }
    return indexMatches;
}

console.log(getMatchIndexes("this is code [table which has [table table [row and rows [table]", "[table"));

在这里摆弄:https://jsfiddle.net/vqqq1wj4/

但是我必须匹配 2 个字符串才能搜索 [table 和 [row] 并添加到索引。目前它只接受 1 个参数进行搜索。我尝试在 while 中添加与 OR 运算符相同的内容,但它不起作用。理想情况下我应该编写以下代码

getMatchIndexes(str, "[table","[row");

它会根据索引和位置正确返回下面的数组。

 [ "[table", "[table", "[row", "[table" ]

最佳答案

使用String#match与使用字符串生成的正则表达式。

function getMatchIndexes(str, ...toMatch) {
  return str.match(
    // generate regex
    new RegExp(
      // iterate over strings
      toMatch.map(function(v) {
        // escape symbols which has special meaning in regex
        return v.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
      // join with pipe operator and specify g for global match
      }).join('|'), 'g'));
}

console.log(getMatchIndexes("this is code [table which has [table table [row and rows [table]", "[table", "[row"));

<小时/>

引用:Converting user input string to regular expression

关于jquery - 使用indexOf()搜索多个字符串并添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41368233/

相关文章:

javascript - 如果 Td 值不匹配,则删除整个 Tr - Javascript

javascript - jquery 求和不起作用

javascript - 测验应用程序 : Buttons in javascript are not functioning

javascript - 使用下划线从 JSON obj 收集数据以创建位置数组

javascript - 在选择中更改选项时更改图像

javascript - Jquery 排序结果不一致

javascript - 物化.css : Expand the first Collapsible div on Page load

javascript - 如何在 Kendo UI 的自动完成模板上设置 `this` 的范围?

javascript - 每个<h3>的第一个字母变成超链接

c# - 在 Jquery 警报中显示表行的所有值