The search() method of the String class in JavaScript is used to search for a match between a regular expression and the calling string.
The syntax of String.search() method is:
search(regexp)
This search() method of String search for a match between a regular expression regexp and the calling string.
Parameter | Optional/Required | Description |
---|---|---|
regexp | required | A regular expression object against which to match the calling string. |
String.search() returns value of type Number
.
In JavaScript, the search()
method can be used to search for a pattern within a string using a regular expression.
For example,
str
with the value 'The quick brown fox jumps over the lazy dog'
.search()
method with a regular expression to search for the pattern 'quick'
.index
.index
to the console using the console.log()
method.const str = 'The quick brown fox jumps over the lazy dog';
const index = str.search(/quick/);
console.log(index);
4
In JavaScript, if no match is found, the search()
method returns -1
.
For example,
str
with the value 'The quick brown fox jumps over the lazy dog'
.search()
method with a regular expression to search for the pattern 'cat'
.index
.index
to the console using the console.log()
method.const str = 'The quick brown fox jumps over the lazy dog';
const index = str.search(/cat/);
console.log(index);
-1
In this JavaScript tutorial, we learned about search() method of String: the syntax and few working examples with output and detailed explanation for each example.