JS Built-ins
StringString.prototype.indexOfbeginner

String.prototype.indexOf() β€” first occurrence only

πŸ“– Usage Example
const str = 'hello world'
str.indexOf('world')    // β†’ 6
str.indexOf('xyz')      // β†’ -1
str.indexOf('l')        // β†’ 2

Use indexOf() to find the index of the first occurrence of a substring, returning -1 if not found.

String.prototype.indexOf() β€” First Occurrence

.indexOf() returns only the first occurrence. Use .lastIndexOf() for the last.

Challenge: Implement firstOccurrence(str, ch) using .indexOf().

firstOccurrence('abacaba', 'a') // β†’ 0
πŸ’‘ Hints (1)
  • β€’ `.indexOf()` stops at the first match and does not continue.