JavaScript . Metacharacter | RegEx Match any Character

The . metacharacter is used to match any character (except newline and/or other line terminators) using a 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 or using a regular expression.

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

Any number of . (dot) metacharacters 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 lines and line terminators. Since I have used i (which stands for case-insensitive), therefore, the word hey having h in lowercase is also included in the match.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!