JavaScript String search()
Syntax & Examples
String.search() method
The search() method of the String class in JavaScript is used to search for a match between a regular expression and the calling string.
Syntax of String.search()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
regexp | required | A regular expression object against which to match the calling string. |
Return Type
String.search() returns value of type Number
.
✐ Examples
1 Using search() method with a regular expression
In JavaScript, the search()
method can be used to search for a pattern within a string using a regular expression.
For example,
- We define a string variable
str
with the value'The quick brown fox jumps over the lazy dog'
. - We use the
search()
method with a regular expression to search for the pattern'quick'
. - The result is stored in the variable
index
. - We log
index
to the console using theconsole.log()
method.
JavaScript Program
const str = 'The quick brown fox jumps over the lazy dog';
const index = str.search(/quick/);
console.log(index);
Output
4
2 Using search() method with a regular expression and no match
In JavaScript, if no match is found, the search()
method returns -1
.
For example,
- We define a string variable
str
with the value'The quick brown fox jumps over the lazy dog'
. - We use the
search()
method with a regular expression to search for the pattern'cat'
. - The result is stored in the variable
index
. - We log
index
to the console using theconsole.log()
method.
JavaScript Program
const str = 'The quick brown fox jumps over the lazy dog';
const index = str.search(/cat/);
console.log(index);
Output
-1
Summary
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.