JavaScript \d and \D Metacharacters | RegEx Match Numbers or Digits

This post is published to provide information about two metacharacters used while working with JavaScript regular expression. That are:

The \d Metacharacter

The \d metacharacter is used when we need to match any digit from 0 to 9. For example:

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

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

   <script>
      let myString = "I got 100% marks in Cyber Security!";
      let pattern = /\d/g;
      document.getElementById("xyz").innerHTML = myString.match(pattern);
   </script>
   
</body>
</html>
Output

Therefore, we can say \d does similar job like [0-9].

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

The \D Metacharacter

Unlike \d, the \D metacharacter character is used to match any character other than digits (0-9). For example:

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

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

   <script>
      let myString = "I got 100% marks in Cyber Security!";
      let pattern = /\D/g;
      document.getElementById("abc").innerHTML = myString.match(pattern);
   </script>
   
</body>
</html>
Output

Therefore, we can say \D does similar job like [^0-9].

JavaScript Online Test


« Previous Tutorial Next Tutorial »