JavaScript String match(): Match RegEx

The JavaScript match() method is used when we need to match a string with or using a regular expression. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "JavaScript is Fun. Is not it?";
      
      const pattern = /s/;
      const res = myString.match(pattern);

      document.getElementById("xyz").innerHTML = res;
   </script>
   
</body>
</html>
Output

That is, the character 's' is matched in the string. To match with all s, use the g modifier in this way:

const pattern = /s/g;

Now the output should be:

The g (which stands for global) modifier is used to find all matches instead of stopping after the first match.

Also, we can use the i modifier to make matching case-insensitive. For example, let me modify the above example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>List of 's' found in the String: <b><span id="x"></span></b></p>

   <script>
      let mystr = "JavaScript is Fun. Is not it?";
      
      const ptr = /s/gi;
      document.getElementById("x").innerHTML = mystr.match(ptr);
   </script>
   
</body>
</html>
Output

List of 's' found in the String:

You can see the output. This time the S, which is in uppercase, has also returned because I have applied the i modifier to force the match to be case-insensitive.

JavaScript match() syntax

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

string.match(search_pattern)

The search_pattern argument is required, which indicates a regular expression that will be used to find a match in the specified string.

The match() method returns an array that contains all matches as its elements. Otherwise, it returns null.

Note: To check whether a specified search_pattern available in the string, use the search() method. The difference between match() and search() is described in a separate post.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!