JS Built-ins
StringString.prototype.indexOfbeginner

String.prototype.indexOf() β€” found returns index

πŸ“– 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()

str.indexOf(searchValue) returns the index of the first occurrence of searchValue, or -1 if not found.

Challenge: Implement findFirst(str, sub) that returns the index of sub in str.

findFirst('hello world', 'world') // β†’ 6
findFirst('hello', 'xyz')         // β†’ -1
πŸ’‘ Hints (1)
  • β€’ `.indexOf()` returns the zero-based index of the first match, or -1.