Search for all instances of a string inside a string
Asked Answered
H

5

15

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?

Honky answered 29/7, 2010 at 18:40 Comment(0)
S
36

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);
Stichomythia answered 29/7, 2010 at 18:56 Comment(1)
I forget so easily that the match object has the "index" property!Lohrman
D
15

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]
Delafuente answered 7/1, 2014 at 9:50 Comment(0)
B
0

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;
}
Bethina answered 29/7, 2010 at 18:47 Comment(1)
Your code doesn't work : - You have an infinite loop if a term is found (indexOf begin at the found pos) - It will always ignore the first occurrence as you test if indexOf(...) > 0 instead of >= 0Delafuente
S
0

You can use indexOf('searchstring', ), using the index returned 'last time round' + 1 until you get -1 back.

Supernational answered 29/7, 2010 at 18:48 Comment(0)
L
0

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;
}
Lohrman answered 29/7, 2010 at 18:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.