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

Jquery 使用indexOf()搜索多个字符串并添加到数组,jquery,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

我有以下工作代码

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"));
在这里拉小提琴:

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

getMatchIndexes(str, "[table","[row");
它将根据它们的索引和位置返回下面的数组

 [ "[table", "[table", "[row", "[table" ]
与使用字符串生成的正则表达式一起使用

函数getMatchIndexes(str,…toMatch){ 返回str.match( //生成正则表达式 新正则表达式( //迭代字符串 toMatch.map(函数(v){ //在正则表达式中具有特殊含义的转义符号 返回v.replace(/[\\{}()[\]^$+*?.]/g,“\\$&”) //使用管道操作符连接并指定g作为全局匹配 }).join(“|”),“g”); }
console.log(getMatchIndexes(“这是代码[表中有[表表表[行和行]表],”[表],“[行])));仅供参考,什么意思?@Themer:这是..或将值作为数组传递……即,
console.log(getMatchIndexes(“这是代码[表中有[表表表]行],[“[表],“[行]]));
&
函数getMatchIndexes(str,toMatch){……
好的,谢谢。最后一件事,如果我现在不太懂正则表达式代码,那我搜索getMatchIndexes(“这是代码[表,它有[表表表表[行和表[表],[“表”,“行]);没有[括号],它应该忽略单词table,但只计算在内)[表和返回相同的输出..@Themer:这将匹配
…o/p=>
[“表”、“表”、“行”、“表”]