JavaScript search(): String Search RegEx

The JavaScript search() method is used when we need to search a substring (value) in a string using a 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:

As you can see that this code is an example of using the search() method in JavaScript to search for a specific substring in a given string. The HTML code includes a paragraph element with a span element inside, which will be used to display the position of the substring in the given string.

The JavaScript code declares a variable myString with the string "JavaScript is Fun." The search() method is then used to find the position of the substring "is" in the myString variable, using a regular expression /is/.

The search() method searches the myString string for the specified substring "is", and returns the position of the first occurrence of the substring in the string. This position is then assigned to the pos variable.

Finally, the position of the "is" substring is displayed inside the span element using the getElementById() method to get the HTML element and then assigning the value of the pos variable to its innerHTML property.

So, the output of this code will be "The word 'is' found at Position: 11" because "is" appears at position 11 in the given string "JavaScript is Fun."

JavaScript search() syntax

The syntax of the search() method in JavaScript is:

string.search(value)

The value argument is required and is used to find the position or index of the 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 exist in the specified string.

Note: If you provide the 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 a substring in a given string, which is indexOf(). But there is little difference between these two, which is described in a separate post. For further information, you can refer to search vs. indexOf().

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

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!