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

String.prototype.search() β€” position of digit

πŸ“– 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() β€” Finding Digits

Use .search() to locate digits in a string.

Challenge: Implement digitPosition(str) that returns the position of the first digit, or -1 if none.

digitPosition('price: 5') // β†’ 7
digitPosition('no digits') // β†’ -1
πŸ’‘ Hints (1)
  • β€’ `/[0-9]/` is equivalent to `/\d/` for matching digit characters.