gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:42:58 25 4
gpt4 key购买 nike

示例:“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);
}

关于javascript - 获取字符串中的匹配数组作为索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36870773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com