search() method executes a search for a match between
a regular expression and this
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
The index of the first match between the regular expression and the given string, or
-1 if no match was found.
When you want to know whether a pattern is found, and also know its index
within a string, use
search(). (If you only want to know if it exists, use
test() method on the
RegExp prototype, which returns a boolean.)
The following example searches a string with two different regex objects to show a
successful search (positive value) vs. an unsuccessful search (
let str = "hey JudE" let re = /[A-Z]/g let reDot = /[.]/g console.log(str.search(re)) // returns 4, which is the index of the first capital letter "J" console.log(str.search(reDot)) // returns -1 cannot find '.' dot punctuation
The definition of 'String.prototype.search' in that specification.
BCD tables only load in the browser