JavaScript String search()
Summary: in this tutorial, you’ll learn how to use the JavaScript String search()
function to locate a substring within a string using a regular expression.
Introduction to the JavaScript String search() function
The search()
method accepts a regular expression and returns the index of the first match in a string:
let index = str.search(regexp);
Code language: JavaScript (javascript)
In this syntax, the regexp
is a regular expression. If you pass a non-RegExp into the method, it will convert that value to a RegExp
.
If the search()
doesn’t find any match, it returns -1.
JavaScript String search() method examples
The following example uses the search()
method to return the first occurrence of any capital letter:
let re = /[A-Z]/;
let str = 'hi There! How are you?';
let index = str.search(re);console.log(index);
Code language: JavaScript (javascript)
Output:
3
Code language: JavaScript (javascript)
It returns 3 which is the index of the capital letter T
.
The following example returns -1
because there is no number in the string:
let re = /[0-9]/;
let str = 'Hello, JavaScript!';
let index = str.search(re);console.log(index);
Code language: JavaScript (javascript)
Output:
-1
Code language: JavaScript (javascript)
Summary
- Use the JavaScript String
search()
to find the index of the first match based on a regular expression in a string.