Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the location of a word in a string without using indexOf?

I have string as this is test for alternative. What I want to find is location of for. I know I could have done this using alert(myString.indexOf("for")), however I don't want to use indexOf.

Any idea/ suggestion for alternative?

jsfiddle

Again, I need this done by Javascript only. No jQuery.. sadly :(

like image 808
Fahim Parkar Avatar asked Dec 13 '25 10:12

Fahim Parkar


2 Answers

.search()?

"this is test for alternative".search("for")
>> 13
like image 118
Barak Avatar answered Dec 15 '25 00:12

Barak


You could code your own indexOf ? You loop on the source string and on each character you check if it could be your searched word.

An untested version to give you an idea:

function myIndexOf(myString, word) {
    var len = myString.length;
    var wordLen = word.length;
    for(var i = 0; i < len; i++) {
        var j = 0;
        for(j = 0; j < wordLen; j++) {
            if(myString[i+j] != word[j]) {
                break;
            }
        }
        if(j == wordLen) {
            return i;
        }
    }

    return -1;
}
like image 28
koopajah Avatar answered Dec 15 '25 00:12

koopajah