logo CodeStepByStep logo

indexOf

Language/Type: JavaScript recursion string return

Write a recursive function named indexOf that accepts two strings s1 and s2 as parameters and that returns the starting index of the first occurrence of the second string s2 inside the first string s1, or -1 if s2 is not found in s1. The table below shows several calls to your function and their expected return values. If s2 is the empty string, always return 0 regardless of the contents of s1. If s2 is longer than s1, it of course cannot be contained in s1 and therefore your function would return -1 in such a case. Notice that case matters; the last example returns -1.

Call Value Returned
indexOf("Barack Obama", "Bar") 0
indexOf("foo", "foo") 0
indexOf("Stanford CS", "ford") 4
indexOf("Barack Obama", "ack") 3
indexOf("Barack Obama", "a") 1
indexOf("sandwich", "") 0
indexOf("Barack Obama", "McCain") -1
indexOf("Barack Obama", "ACK") -1

Constraints:

  • Your solution must not use any loops; it must be recursive.

Function: Write a JavaScript function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.