2016-12-28 101 views
1

我有以下工作代码。使用indexOf()搜索多个字符串并将其添加到数组

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要搜索的字符串表和[行并添加到索引。目前它只接受1个参数进行搜索。我试着在OR中加入相同的操作符,但它不起作用。理想情况下,我应该写下面的代码

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

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

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

回答

3

使用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

+1

感谢Pranav :)就像一个魅力.. – Themer

+0

只是为了refernce有哪些呢?手段? – Themer

+1

@Themer:[spread operator](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator)..或将值作为数组传递......也就是'console.log(getMatchIndexes(“这是代码[表中有[table table [row and rows [table]”,[“[table”,“[row”]]));'&'function getMatchIndexes( str,toMatch){....' –

相关问题