JS Built-ins
← String119 / 195
StringString.prototype.searchbeginner

String.prototype.search() β€” vs indexOf comparison

πŸ“– Usage Example
'hello world'.search(/world/)   // β†’ 6
'hello'.search(/d/)           // β†’ -1
'abc123'.search(/[0-9]/)       // β†’ 3

Use search() to find the index of the first regex match in a string, returning -1 if not found.

String.prototype.search() vs indexOf

Both return the index of a match or -1. search accepts regex; indexOf accepts only strings.

Challenge: Implement firstLetterIndex(str) that returns the index of the first letter using search.

firstLetterIndex('123abc') // β†’ 3
firstLetterIndex('hello')  // β†’ 0
πŸ’‘ Hints (1)
  • β€’ `str.search(/[a-zA-Z]/)` behaves like `str.indexOf` for literals but supports patterns.