admin管理员组

文章数量:1287878

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 :(

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 :(

Share Improve this question edited Mar 14, 2015 at 0:38 Mark Fox 8,9249 gold badges56 silver badges77 bronze badges asked Dec 2, 2012 at 12:16 Fahim ParkarFahim Parkar 31.6k46 gold badges168 silver badges282 bronze badges 4
  • 5 "however I don't want to use indexOf." Why not? Without that information, the question is pretty strange. – T.J. Crowder Commented Dec 2, 2012 at 12:25
  • 1 Always include all relevant code and markup in the question itself, don't just link. meta.stackexchange./questions/118392/… – T.J. Crowder Commented Dec 2, 2012 at 12:26
  • @T.J.Crowder : I just wanted to know alternate way... that's it... any more questions for me? – Fahim Parkar Commented Dec 2, 2012 at 12:29
  • 1 @ Fahim: "I just wanted to know alternate way" Again, why? For what purpose? Is there any reason for needing an alternative? From the FAQ: "You should only ask practical, answerable questions based on actual problems that you face" – T.J. Crowder Commented Dec 2, 2012 at 12:35
Add a ment  | 

2 Answers 2

Reset to default 5
.search()?

"this is test for alternative".search("for")
>> 13

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

本文标签: alternative to indexOf in JavascriptStack Overflow