Rami Salim
Rami Salim

Reputation: 192

How to get the index of match string in JS

I am trying to get the index of the exact search string, I have built a function that returns the index the match strings where I need to get the index only with the exact match

here is my function

getIndicesOf = (searchStr, str) => {
              var searchStrLen = searchStr.length;
              if (searchStrLen === 0) {
                return [];
              }
              var startIndex = 0,
                index,
                indices = [];
              while ((index = str.indexOf(searchStr, startIndex)) > -1) {
                indices.push(index);
                startIndex = index + searchStrLen;
              }
               console.log("detercting " , indices );
            return indices;
};
console.log(getIndicesOf("go" , "go, I am going ")); //  [0, 9]

here I go the index of go and going , How can get the index only of the exact match string?

Upvotes: 0

Views: 744

Answers (2)

Nitha
Nitha

Reputation: 680

The first occurrence of go also contains a comma. So it is not an exact match.

If you still want to get all the indices of go and go, in the words array, you can use the following script.

var x = "go, I am going go";
arr = x.split(" ");
arr.map((e, i) => (e === "go" || e === "go,") ? i : '').filter(String)

If you need to find the index in the string you can use the below approach

var x = "go, I am going go";
arr = x.split(" "); var index = 0;
arr.map((e, i) => {
     var occur = (e === "go" || e === "go,") ? index : '';
     index+=e.length+1;
     return occur}).filter(String)

Upvotes: 2

Dhiren
Dhiren

Reputation: 143

replace your while loop with this code,

 while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        if(str.substring(startIndex,searchStrLen) == searchStr)
        {
                indices.push(index);
                startIndex = index + searchStrLen;
        }
}

Upvotes: 1

Related Questions