JavaScript search() | String Search RegEx

The JavaScript search() method is used when we need to search a substring (value) in a string using regular expression. For example:

HTML with JavaScript Code
<!DOCTYPE html>

   <p>The word 'is' found at Position: <b><span id="x"></span></b></p>

      let myString = "JavaScript is Fun.";
      let pos =;
      document.getElementById("x").innerHTML = pos;

The word 'is' found at Position:

JavaScript search() Syntax

The syntax of search() method in JavaScript is:

The value argument is required, used to find the position or index of first match in the specified string.

The search() method return the index number of the specified value in the specified string. Otherwise return -1 if the specified value does not exists in the specified string.

Note: If you provide a string itself as the search value, then it will be converted into a regular expression automatically.

Note: There is another method available in JavaScript, that can be used to find the position of substring in a given string, which is indexOf(). But there is little difference between these two, which is described in its separate tutorial. For further information, you can refer to search Vs. indexOf().

Note: To get all matches, use match() method. The difference between match() and search() is described in its separate tutorial.

JavaScript Online Test

« Previous Tutorial Next Tutorial »

Liked this article? Share it!

Like/follow us on social media for updates!