获取字符串中的匹配项数组作为索引

Get an array of matches in string as indexes

本文关键字:数组 索引 字符串 获取      更新时间:2023-09-26
示例: "abc

abc ab a".indexOfList("abc") 返回 [0,4]

我的代码:

String.prototype.indexOfList=function(word){
    var l=[];
    for(var i=0;i<this.length;i++){ //For each character
        var pushed=(this[i]==word[0])&&(word.length+i<=this.length);
        if (pushed) {
            for(var j=1;j<word.length;j++){
                if (word[j]!=this[i+j]) {
                    pushed=false; break;
                }
            }
        }
        if (pushed) {
            l.push(i);
        }
    }
    return l;
}

有没有比这更好、更小的方法?

您可以使用正则表达式match命令:

var re = /abc/g,
str = "abc abc ab a";
var pos = [];
while ((match = re.exec(str)) != null) {
    pos.push(match.index);
}

有一个版本可以处理重叠的字符串,即字符串的模式aaa aaaaa应该返回[0,1,2]

function indexOfList(needle, haystack) {
  const result = [];
  let i = 0;
  while (haystack.includes(needle, i)) {
    const match = haystack.indexOf(needle, i);
    result.push(match);
    i = match + 1;
  }
  return result;
}
indexOfList("abc", "abc abc ab a"), // [0, 4]
indexOfList("aaa", "aaaabc abc ab a") // [0, 1]

我还建议不要扩展本机对象的原型。这可能会导致非常讨厌的名字冲突。

考虑一下你的同事(甚至是语言维护者)添加了一个同名的函数。

indexOf函数

var str = "abc abc ab a";
var i = -1;
var result = [];
while (true) {
    i = str.indexOf("abc", i + 1);
    if (i == -1) break;
    result.push(i);
}
document.write(result);

没有必要把事情复杂化。与此非常相似的方法已经存在:String.indexOf。

您还可以将第二个参数传递给此方法,告诉它从何处开始查找。如果继续增加第二个参数,则可以快速找到每个匹配项。

String.prototype.indexOfList = function(word) {
    var start = this.indexOf(word);
    var l = [start]
    if(start == -1) {
        return [-1, -1];
    }
    var index = start;
    for(var i = start + word.length; i < this.length - word.length; i = index) {
        index = this.indexOf(word, i);
        if(index == -1) {
            break;
        }
        l.push(index);
    }
    return l;
}

这将从第一次出现时开始,并继续添加单词出现的每个索引。

您可以使用replace

String.prototype.indexOfList = function(word){
    var l=[];
    this.replace(new RegExp(word,"g"), (a,i) => l.push(i));
    return l;
}
console.log("abc abc ab a".indexOfList("abc"));