String.prototype.search
Returns the position of the first regex match.
Available since: ES3
Syntax
str.search(regexp)Parameters
| Parameter | Type | Description |
|---|---|---|
| regexp | RegExp | A regular expression. |
Return value
numberThe position of the first match, or -1.
Examples
Where the first digit is:
console.log('Room A12'.search(/\d/));
console.log('Room A'.search(/\d/));Output:
6
-1Notes
It is indexOf() for regular expressions. If you only need to know whether there is a match, regex.test(str) is simpler.
See also
- String.prototype.indexOf — Finds the position of the first occurrence of a substring.
- RegExp.prototype.test — Checks whether a string matches a pattern.
Related recipes
In the tutorial
- Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.