Computer >> Computer tutorials >  >> Programming >> Javascript

\d vs \D in JavaScript?


\d vs \D

There is a lot of difference between \d and \D in which the former results in the digits and the latter results in the non-digits such as e,^, etc. These are used along with global object "g" so that all the digits and non-digits across a text will be displayed in the output. Let's discuss it in detail.

syntax-1

new RegExp("\\d", "g");

syntax-2

new RegExp("\\D", "g")

Example-1

In the following example, '\d' is used along with the global object "g" to get all the digits from the provided text. If the global object is not used, then only the first digit will be displayed in the output. 

 

<html>
<body>
<script>
   var text = "one has to score 760+ in gmat to get into ivy colleges";
   var regpat = /\d/g;
   var result = text.match(regpat);
   document.write(result);
</script>
</body>
</html>

Output

7,6,0


Example-2

In the following example, \D\ is used along with global object 'g' to get all the non-digit characters such as t, y, ^, &, etc. Non-digit characters can include -, ^, &, etc and also can include spaces. 

<html>
<body>
<script>
   var text = "one has to score 760+ in gmat to get into ivy colleges";
   var regpat = /\D/g;
   var result = text.match(regpat);
   document.write(result);
</script>
</body>
</html>

Output

o,n,e, ,h,a,s, ,t,o, ,s,c,o,r,e, ,+, ,i,n, ,g,m,a,t, ,t,o, ,g,e,t, ,i,n,t,o, ,i,v,y, ,c,o,l,l,e,g,e,s