JavaScript . Metacharacter | RegEx Match any Character

The . metacharacter is used to match any character (except newline and/or other line terminators) using JavaScript regular expression. For example:

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

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

   <script>
      let myString = "Hello Okay Not Good Hey Hello";
      let pattern = /H.l/g;
      document.getElementById("xyz").innerHTML = myString.match(pattern);
   </script>
   
</body>
</html>
Output

Note: The match() method is used to match a string with/using a regular expression.

The g after /H.l/ stands for global, and is used to match with all combination of three characters that starts with H followed by any character (except new line and line terminators) and ends with l. If we remove that g, then the program stops after the first match.

Any number of . (dot) metacharacter can be used in any combination when we need to apply a match for any character. For example:

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

   <p id="abc"></p>

   <script>
      let mystr = "Hello Okay Not Good hey Hello";
      let ptrn = /H../gi;
      document.getElementById("abc").innerHTML = mystr.match(ptrn);
   </script>
   
</body>
</html>
Output

That is, the /H../gi regular expression matches every combination of three characters that starts with H followed by any two characters except new line and line terminators. Since I have used i (stands for case-insensitive), therefore that word hey having h in lowercase also included in the match.

JavaScript Online Test


« Previous Tutorial Next Tutorial »