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>
<html>
<body>

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

   <script>
      let myString = "JavaScript is Fun.";
      let pos = myString.search(/is/);
      document.getElementById("x").innerHTML = pos;
   </script>
   
</body>
</html>
Output

The word 'is' found at Position:

JavaScript search() Syntax

The syntax of search() method in JavaScript is:

string.search(value)

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 »



Like/Share Us on Facebook 😋