3

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

4
  • 7
    "however I don't want to use indexOf." Why not? Without that information, the question is pretty strange. 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.com/questions/118392/… 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? 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" Commented Dec 2, 2012 at 12:35

2 Answers 2

4
.search()? "this is test for alternative".search("for") >> 13 
Sign up to request clarification or add additional context in comments.

3 Comments

@FahimParkar: Note that search is not a direct replacement for indexOf. For example, "10 * 5 = 50".indexOf("*") is 3, but "10 * 5 = 50".search("*") throws an error. "Hi, my name is Joe.".indexOf(".") is 18 but "Hi, my name is Joe.".search(".") is 0.
@T.J.Crowder That is because search expects a regex argument. In your example, "Hi, my name is Joe.".search("\\.") yields the expected value of 18. To clarify, .search, expecting a RegEx, should not be directly fed a string (but it can be). So, the above expectation would normally be "Hi, my name is Joe.".search(/\./)
@Akiva: I know. The point is that it's not a direct replacement.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.