String. prototype. search()
Returns the index of the first match of a regular expression in a string, or -1.
- Returns
- The index of the first match, or
-1when the pattern does not match anywhere. - Changes the original
- No
Example
#const code = 'Discount code: CODE2026'
console.log(code.search(/\d/))
console.log(code.search(/[A-Z]{4}/))
console.log(code.search(/python/i))Definition and usage
#The search() method checks a string against a regular expression and returns the position where the first match starts. When the pattern does not match anywhere, the result is -1. So it works like indexOf(), but it searches for a pattern instead of fixed text.
That lets you find the first digit in a text, the first uppercase letter, or a word written in any letter case (the i flag). If you pass a plain string, it gets converted to a regular expression, so characters like . or ? keep their special meaning.
The method always searches from the start of the string and ignores the g flag and the lastIndex property. When you need the matched text itself, use match(), and for a simple matches-or-not answer, regex.test(text) is enough.
Syntax
#string.search(regexp)Parameters
#regexp
RegExp | string
A regular expression. A plain string gets converted to one vianew RegExp().
More examples
#const title = 'Lesson 12: Loops'
console.log(title.indexOf('12'))
console.log(title.search(/\d+/))
console.log(title.indexOf('.'))
console.log(title.search('.'))There is no period in the title, yet search(".") still returned 0. The string turned into a regular expression, where a dot means any character.
const address = '42 Flower Street, 00-950 Springfield'
const start = address.search(/\d{2}-\d{3}/)
console.log(start)
console.log(address.slice(start, start + 6))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- A string you pass in becomes a regular expression, so
"1.5".search(".")returns0, because a dot matches any character. UseindexOf()to search for fixed text. - A result of
0means a match right at the start, not the absence of one. Compare the result against-1.
Related entries
#- String.prototype.indexOf()Returns the index of the first occurrence of the given text in a string, or -1 when it is not there.
- String.prototype.match()Matches a string against a regular expression. Returns an array with the match or all matches, or null.
- RegExpA regular expression: a pattern for searching, validating, and replacing pieces of text.
- String.prototype.matchAll()Returns an iterator over all the matches of a regular expression, each one together with its groups and position in the text.
Spotted a mistake or missing an example? Write to us.