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);

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);

Output:

3

#javascript #programming #developer #web-development

How to use the JavaScript String Search() Function
2.05 GEEK