0

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?

4
  • What output were you expecting instead? Commented Nov 30, 2018 at 4:01
  • The first occurance of go also contains a semicolon. "go," so it is not an exact match. right ? Commented Nov 30, 2018 at 4:04
  • the first one is an exact match but the second one is not , So I do not want to get the index of it Commented Nov 30, 2018 at 4:07
  • Your str is "go, I am going " which contains no semicolons? Did you want to forbid commas after the "o"? Or did you want to forbid more words after the "o"? (with those conditions, nothing will be matched given your input) Commented Nov 30, 2018 at 4:07

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I prefer this approach I am going to try it in my code can't tell if it will work because I am using draf.js with my react.js application thank you so much dude
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.