在字符串中搜索字符串的所有实例 [英] Search for all instances of a string inside a string

查看:43
本文介绍了在字符串中搜索字符串的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用 indexOf 方法来搜索另一个字符串中是否存在一个字符串.但是我想获取字符串所在的所有位置?有什么方法可以获取字符串存在的所有位置吗?

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?

<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?

推荐答案

尝试类似:

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);

这篇关于在字符串中搜索字符串的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆