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 expressions. That are:

The \d metacharacter in JavaScript RegEx

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

In the above example, the following HTML code:

is an empty paragraph element with the ID "xyz". The ID attribute is used to uniquely identify a document element. Now, the following JavaScript statement:

let myString = "I got 100% marks in Cyber Security!";

declares a variable named "myString" and assigns it a string value of "I got 100% marks in Cyber Security!".

Then the following (second) JavaScript statement:

let pattern = /\d/g;

declares a variable named "pattern" and assigns it a regular expression value of /\d/g. This regular expression matches any digit character in a string. Finally, the following (last) JavaScript statement:

document.getElementById("xyz").innerHTML = myString.match(pattern);

uses the getElementById() method to get the HTML element with the ID "xyz" and sets its innerHTML property to the result of calling the match() method on the "myString" variable with the "pattern" regular expression. The match() method returns an array of all the digit characters in the "myString" variable.

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

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

The \D metacharacter in JavaScript RegEx

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 a similar job to [^0-9].

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!