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

String.prototype.search() β€” returns index of first match

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

str.search(regexp) returns the index of the first match of regexp, or -1 if not found.

Challenge: Implement findDigitIndex(str) that returns the index of the first digit.

findDigitIndex('abc3def') // β†’ 3
findDigitIndex('hello')   // β†’ -1
πŸ’‘ Hints (1)
  • β€’ `str.search(/\d/)` returns the index of the first digit character.