Javascript 在字符串中搜索字符串的所有实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3365902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search for all instances of a string inside a string
提问by sai
Hello I am using indexOf method to search if a string is present inside another string. But I want to get all the locations of where string is? Is there any method to get all the locations where the string exists?
您好,我正在使用 indexOf 方法来搜索另一个字符串中是否存在字符串。但我想获取字符串所在的所有位置?有没有办法获取字符串存在的所有位置?
<html>
<head>
<script type="text/javascript">
function clik()
{
var x='hit';
//document.getElementById('hideme').value ='';
document.getElementById('hideme').value += x;
alert(document.getElementById('hideme').value);
}
function getIndex()
{
var z =document.getElementById('hideme').value;
alert(z.indexOf('hit'));
}
</script>
</head>
<body>
<input type='hidden' id='hideme' value=""/>
<input type='button' id='butt1' value="click click" onClick="clik()"/>
<input type='button' id='butt2' value="clck clck" onClick="getIndex()"/>
</body>
</html>
Is there a method to get all positions?
有没有办法获得所有职位?
回答by cic
Try something like:
尝试类似:
var regexp = /abc/g;
var foo = "abc1, abc2, abc3, zxy, abc4";
var match, matches = [];
while ((match = regexp.exec(foo)) != null) {
matches.push(match.index);
}
console.log(matches);
回答by Congelli501
Here is a working function:
这是一个工作函数:
function allIndexOf(str, toSearch) {
var indices = [];
for(var pos = str.indexOf(toSearch); pos !== -1; pos = str.indexOf(toSearch, pos + 1)) {
indices.push(pos);
}
return indices;
}
Use example:
使用示例:
> allIndexOf('dsf dsf kfvkjvcxk dsf', 'dsf');
[0, 4, 18]
回答by Kiersten Arnold
I don't know if there's a built in function to do it. You could do it in a simple loop though:
我不知道是否有内置函数可以做到这一点。你可以在一个简单的循环中做到这一点:
function allIndexes(lookIn, lookFor) {
var indices = new Array();
var index = 0;
var i = 0;
while(index = lookIn.indexOf(lookFor, index) > 0) {
indices[i] = index;
i++;
}
return indices;
}
回答by Will A
You can use indexOf('searchstring', ), using the index returned 'last time round' + 1 until you get -1 back.
您可以使用 indexOf('searchstring', ),使用返回的索引 'last time round' + 1,直到返回 -1。
回答by Pointy
Here's a regex way to do it:
这是执行此操作的正则表达式方法:
function positions(str, text) {
var pos = [], regex = new RegExp("(.*?)" + str, "g"), prev = 0;
text.replace(regex, function(_, s) {
var p = s.length + prev;
pos.push(p);
prev = p + str.length;
});
return pos;
}

