我有以下工作代码。
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"));
关于jquery - 使用indexOf()搜索多个字符串并添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41368233/