JavaScript String match() | Match RegEx

The JavaScript match() method is used when we need to match a string with/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 g modifier in this way:

const pattern = /s/g;

Now the output should be:

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

Also we can use the i modifier to allow matching go 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 also has returned, because I have applied the i modifier to force the match go case-insensitive.

JavaScript match() Syntax

The syntax of match() method in JavaScript is:

string.match(search_pattern)

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

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

Note: To check whether a specified search_pattern available in the string, use search() 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 😋