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" ]
感谢Pranav :)就像一个魅力.. – Themer
只是为了refernce有哪些呢?手段? – Themer
@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){....' –