Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

javascript - Search for all instances of a string inside a string

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...