Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript RegExp \D( non-digit characters) Metacharacter
Next article icon

JavaScript RegExp \d Metacharacter

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript regular expressions, the \d metacharacter is used to match any digit character (0-9). This is a shorthand for the character class [0-9], which matches any single character within the specified range.

To begin, let’s look at a simple example where we use \d to match digits in a string.

JavaScript
let s = "The year is 2024 and the month is 12."; let regex = /\d+/g;  let match = s.match(regex); console.log(match); 

Output
[ '2024', '12' ] 
  • The regular expression /\d+/g is used to match one or more digits globally in the string.
  • The \d+ part ensures that we match one or more consecutive digits.
  • The g flag indicates a global search, meaning it will find all matches in the string, not just the first one.

1. Match Exactly One Digit

You can also use \d to match a single digit in a string. Let’s see how to match only one digit.

JavaScript
let s = "The code 5 is valid, but 15 is too long."; let regex = /\d/;  let match = s.match(regex); console.log(match); 

Output
[   '5',   index: 9,   input: 'The code 5 is valid, but 15 is too long.',   groups: undefined ] 
  • The regular expression /\d/ will match the first digit it finds in the string.
  • In this case, the match is “5”, which is the first digit in the string.
  • Since we’re only looking for one digit, it stops after finding the first match.

2. Using \d with Anchors

You can combine the \d metacharacter with anchors like ^ (start of string) or $ (end of string) to match digits in specific positions in the string.

JavaScript
let s = "Year2024"; let regexS = /^\d+/; let regexE = /\d+$/;  console.log(s.match(regexS)); console.log(s.match(regexE)); 

Output
null [ '2024', index: 4, input: 'Year2024', groups: undefined ] 
  • The regular expression /^\d+/ matches one or more digits at the start of the string.
  • The regular expression /\d+$/ matches one or more digits at the end of the string.
  • In both cases, the match is “2024”, as it appears at both the start and end of the string.

3. Matching Numbers with \d and Other Characters

You can use \d to match digits in more complex patterns, like when digits are surrounded by non-digit characters.

JavaScript
let s = "Order123 has been shipped."; let regex = /\d+/;  let match = s.match(regex); console.log(match); 

Output
[   '123',   index: 5,   input: 'Order123 has been shipped.',   groups: undefined ] 
  • The regular expression /\d+/ is used to match one or more digits in the string “Order123 has been shipped.”
  • The match is “123”, which is found between the words “Order” and “has”.

4. Using \d for Validating Numbers

The \d metacharacter is frequently used for validating numerical patterns, such as checking if a string is a valid number or phone number.

JavaScript
let phone = "123-456-7890"; let regex = /^\d{3}-\d{3}-\d{4}$/;  let isValid = regex.test(phone); console.log(isValid); 

Output
true 
  • The regular expression /^\d{3}-\d{3}-\d{4}$/ ensures that the string matches a specific phone number format (XXX-XXX-XXXX).
  • The \d{3} matches exactly three digits, and the – matches the hyphen between the digit groups.
  • The ^ and $ anchors ensure that the pattern matches the entire string from start to end.
  • The test() method checks if the phone number is in the correct format and returns true if it matches.

Key Points to Remember

  • \d matches a single digit (equivalent to [0-9]).
  • \d+ can match one or more digits.
  • The g flag allows you to find all matches in a string.
  • \d is commonly used for matching numbers, validating phone numbers, dates, or any other patterns that involve digits.
  • Combine \d with anchors (^, $) to restrict the match to specific positions in the string (e.g., start or end).


Next Article
JavaScript RegExp \D( non-digit characters) Metacharacter

V

Vishal Chaudhary 2
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-RegExp

Similar Reads

  • JavaScript RegExp() Constructor
    The RegExp() constructor in JavaScript allows you to create a regular expression object that can be used to match patterns in strings. This method is particularly useful when you need to dynamically create regular expressions from strings or variables. [GFGTABS] JavaScript let pat = "hello
    2 min read
  • JS RegExp Properties

    • JavaScript RegExp Constructor Property
      The constructor property of a JavaScript RegExp object returns a reference to the function that created the regular expression. This property typically points to the built-in RegExp function. [GFGTABS] JavaScript // Creating a regular expression let regex = /test/; // Checking the constructor proper
      2 min read

    • JavaScript RegExp dotAll Property
      The dotAll property in JavaScript regular expressions determines whether the 's' (dotAll) flag is enabled. This flag modifies the behaviour of the dot (.) metacharacter, allowing it to match any character, including line terminators like \n, \r, and others. Without the s flag, the dot (.) matches an
      3 min read

    • JavaScript RegExp Flags Property
      RegExp flags are a set of optional characters added to the regular expression pattern to control its behavior. Flags modify how the pattern is interpreted during the search. They can be added after the closing / of the regular expression pattern. [GFGTABS] JavaScript let s = "Hello World\nhello
      3 min read

    • JavaScript RegExp global Property
      The global property in JavaScript regular expressions indicates whether the g (global) flag is enabled. A regular expression with the g flag searches for all matches in the input string rather than stopping after the first match. [GFGTABS] JavaScript // Regular expression without 'g' flag le
      2 min read

    • JavaScript RegExp hasIndices Property
      The hasIndices property in JavaScript regular expressions indicates whether the d (indices) flag is enabled. When the d flag is set, the regular expression captures the start and end indices of the matched substring within the input string, providing detailed positional information. [GFGTABS] JavaSc
      3 min read

    • JavaScript RegExp ignoreCase Property
      The ignoreCase property in JavaScript regular expressions determines whether the i (ignore case) flag is enabled. A regular expression with the i flag performs a case-insensitive match, meaning it ignores differences between uppercase and lowercase characters during the matching process. [GFGTABS] J
      2 min read

    • JavaScript RegExp multiline Property
      The multiline property of a JavaScript regular expression indicates whether the m (multiline) flag is enabled. When enabled, the ^ and $ anchors match the start and end of each line within a string, rather than the entire string. [GFGTABS] JavaScript // Regular expression without 'm' flag le
      3 min read

    • JavaScript RegExp source Property
      The source property of a JavaScript regular expression object returns the text of the pattern used to create the RegExp object, without the enclosing slashes or flags. This property is read-only and reflects the original pattern as a string. [GFGTABS] JavaScript // Creating a regular expression let
      2 min read

    • JavaScript RegExp Sticky Property
      The sticky property in JavaScript regular expressions determines whether the y (sticky) flag is enabled. A sticky regular expression searches for a match starting from the current position in the target string and does not search further if a match isn't found at that exact point. [GFGTABS] JavaScri
      3 min read

    • JavaScript RegExp unicode Property
      The unicode property of a JavaScript regular expression object indicates whether the u (Unicode) flag is enabled. When this flag is set, the regular expression operates in full Unicode mode, allowing correct handling of Unicode characters, such as surrogate pairs, Unicode code points, and properties
      2 min read

    • JavaScript RegExp lastIndex Property
      The lastIndex property of a JavaScript regular expression object indicates the index at which to start the next match. This property is particularly useful when using methods like exec() or test() in combination with global (g) or sticky (y) flags. [GFGTABS] JavaScript let regex = /test/g; // Regula
      3 min read

    JS RegExp Methods

    • JavaScript RegExp exec() Method
      The RegExp.exec() method in JavaScript allows you to search for a pattern in a string and retrieve detailed information about the match. Unlike simple methods like test(), exec() returns not just a boolean, but an array containing the entire match, capturing groups, the position of the match, and mo
      2 min read

    • JavaScript RegExp test() Method
      The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false. [GFGTABS] JavaScript const pattern = /hello/; const text = "hello world"; console.log(pattern.test(text)); [/GFGTABS]Outputtrue SyntaxRegExpObje
      1 min read

    • JavaScript RegExp toString() Method
      The RegExp.toString() method in JavaScript is used to return the string representation of a regular expression object. It converts the regular expression to a string, including its pattern and flags. [GFGTABS] JavaScript let reg1 = /hello/i; let reg2 = /\d{3}-\d{2}-\d{4}/; console.log(reg1.toString(
      2 min read

    JS RegExp Quantifier

    • JavaScript RegExp ? Quantifier
      The ? quantifier in JavaScript regular expressions specifies that the preceding element is optional. It matches zero or one occurrence of the element, making it a useful tool for flexible pattern matching. [GFGTABS] JavaScript let regex = /colou?r/; let str1 = "color"; let str2 = "col
      2 min read

    • JavaScript RegExp + Quantifier
      The m+ Quantifier in JavaScript is used to find the match of any string that contains at least one m. [GFGTABS] JavaScript let str = "GeeksforGeeks@_123_$"; let regex = /G+/gi; let match = str.match(regex); console.log("Found " + match.length + " matches: " + match); [/
      1 min read

    • JavaScript RegExp * Quantifier
      The RegExp m* Quantifier in JavaScript is used to find the match of any string that contains zero or more occurrences of match. [GFGTABS] JavaScript let str = "GeeksforGeeks@_123_G$"; let regex = /ke*/gi; let match = str.match(regex); console.log("Found " + match.length + "
      1 min read

    • JavaScript RegExp ?! Quantifier
      The RegExp ?!m Quantifier in JavaScript is used to find the match of any string which is not followed by a specific string m. [GFGTABS] JavaScript // 3-digits not followed by any numbers const str = "123Geeks12345@"; const regex = /\d{3}(?!\d)/g; const match = str.match(regex); console.log
      1 min read

    • JavaScript RegExp ^ Quantifier
      The ^ in JavaScript regular expressions is a special anchor that matches the beginning of a string or the start of a line when the multiline (m) flag is used. It is not a quantifier but an assertion used to control where matching starts in a string. [GFGTABS] JavaScript let regex = /^hello/; let str
      3 min read

    • JavaScript RegExp $ Quantifier
      The RegExp m$ Quantifier in JavaScript is used to find the match of any string which contains m at the end of it. [GFGTABS] JavaScript let str = "Geeksforh\nGeeks@_h"; let regex = /h$/gim; let match = str.match(regex); console.log("Found " + match.length + " matches: "
      1 min read

    • JavaScript RegExp {X,} Quantifier
      The RegExp m{X, } Quantifier in JavaScript is used to find the match of any string that contains a sequence of m, at least X times, where X is a number. [GFGTABS] JavaScript let str = "GeeksforGeeeks e@_123_$"; let regex = /k{1,}/gi; let match = str.match(regex); console.log("Found
      1 min read

    • JavaScript RegExp {X} Quantifier
      The RegExp m{X} Quantifier in JavaScript is used to find the match of any string that contains a sequence of m, X times where X is a number. [GFGTABS] JavaScript let str = "Geekkkksss@_123_$"; let regex = /k{2}/gi; let match = str.match(regex); console.log(match); [/GFGTABS]Output[ 'kk', '
      1 min read

    • JavaScript RegExp {X,Y} Quantifier
      JavaScript RegExp {X,Y} Quantifier in JavaScript is used to find the match of any string that contains a sequence of m, X to Y times where X, Y must be numbered. [GFGTABS] JavaScript // Matches between 2 and 4 digits const regex = /\d{2,4}/; console.log(regex.test("123")); console.log(rege
      2 min read

    JS RegExp Modifier

    • JavaScript RegExp g Modifier
      The g (global) modifier in JavaScript regular expressions is used to perform a global search. It ensures the pattern is matched multiple times throughout the entire string, rather than stopping at the first match. [GFGTABS] JavaScript let regex = /cat/g; let str = "cat, caterpillar, catch a cat
      3 min read

    • JavaScript RegExp i Modifier
      The i modifier in JavaScript regular expressions stands for case-insensitivity. It allows the regex to match letters in a string regardless of their case, making it ideal for scenarios where matching should not be case-sensitive, such as user input validation or text search. When the i flag is activ
      2 min read

    • JavaScript RegExp m Modifier
      The m modifier in JavaScript regular expressions stands for "multiline". It alters the behavior of the ^ (caret) and $ (dollar) anchors, allowing them to match the start or end of any line in a multiline string, rather than just the start or end of the entire string. [GFGTABS] JavaScript let regex =
      3 min read

    JS RegExp Expression

    • JavaScript RegExp [abc] Expression
      The RegExp [abc] Expression in JavaScript is used to search any character between the brackets. The character inside the brackets can be a single character or a span of characters. [A-Z]: It is used to match any character from uppercase A to Z.[a-z]: It is used to match any character from lowercase
      2 min read

    • JavaScript RegExp (x|y) Expression
      The (x|y) expression in JavaScript regular expressions is used to match either x or y. It acts as an OR operator in regular expressions, allowing you to specify multiple patterns to match. [GFGTABS] JavaScript let regex = /(cat|dog)/g; let str = "I have a cat and a dog."; let matches = str
      2 min read

    • JavaScript RegExp [0-9] Expression
      The [0-9] expression in JavaScript regular expressions matches any single digit between 0 and 9. It is a character class used to represent a range of numeric characters. [GFGTABS] JavaScript let regex = /[0-9]/g; let str = "abc123xyz"; let matches = str.match(regex); console.log(matches);
      3 min read

    • JavaScript RegExp [^0-9] Expression
      The RegExp [^0-9] Expression in JavaScript is used to search any digit which is not between the brackets. The character inside the brackets can be a single digit or a span of digits. Example: Finding non-digit characters from given string [GFGTABS] JavaScript const regex = /[^0-9]/g; const str =
      2 min read

    JS RegExp Metacharacter

    • JavaScript RegExp . Metacharacter
      The . metacharacter in JavaScript regular expressions matches any single character except for a newline (\n) or other line terminators, such as \r. It is widely used as a wildcard to represent "any character." [GFGTABS] JavaScript let regex = /c.t/; let str1 = "cat"; let str2 = "cut
      3 min read

    • JavaScript RegExp \b Metacharacter
      The \b metacharacter in JavaScript regular expressions represents a word boundary, allowing you to match positions where a word begins or ends. A word boundary is the position between a word character (\w: letters, digits, or underscores) and a non-word character (\W: everything else, including spac
      3 min read

    • JavaScript RegExp \B Metacharacter
      The \B metacharacter in JavaScript regular expressions matches a position where a word boundary does not exist. It is essentially the opposite of the \b (word boundary) metacharacter. [GFGTABS] JavaScript let regex = /\Bcat\B/; let str1 = "concat"; let str2 = "cat"; console.log(r
      2 min read

    • JavaScript RegExp \d Metacharacter
      In JavaScript regular expressions, the \d metacharacter is used to match any digit character (0-9). This is a shorthand for the character class [0-9], which matches any single character within the specified range. To begin, let's look at a simple example where we use \d to match digits in a string.
      3 min read

    • JavaScript RegExp \D( non-digit characters) Metacharacter
      The RegExp \D Metacharacter in JavaScript is used to search non-digit characters i.e all the characters except digits. It is the same as [^0-9]. [GFGTABS] JavaScript let str = "a1234g5g5"; let regex = /\D/g; let match = str.match(regex); console.log("Found " + match.length +
      1 min read

    • JavaScript RegExp \f Metacharacter
      The \f metacharacter in JavaScript regular expressions matches a form feed character. Form feed (\f) is a control character used to indicate a page break in text. While it is rare in modern applications, it can still appear in old documents or text files. [GFGTABS] JavaScript let regex = /\f/; let s
      2 min read

    • JavaScript RegExp \n Metacharacter
      The \n metacharacter in JavaScript regular expressions matches a newline character. It is used to identify line breaks in strings, enabling developers to process multi-line text effectively. [GFGTABS] JavaScript let regex = /\n/; let str = "Hello\nWorld"; console.log(regex.test(str)); [/GF
      2 min read

    • JavaScript RegExp \v (vertical tab character) Metacharacter
      The RegExp \v Metacharacter in JavaScript is used to find the vertical tab character. If it is found it returns the position else it returns -1. [GFGTABS] JavaScript let str = "G\vFG@_123_$"; let regex = /\v/; let match = str.search(regex); if (match == -1) { console.log("No vertical
      1 min read

    • JavaScript RegExp \t Metacharacter
      The RegExp \t Metacharacter in JavaScript is used to find the tab character. If it is found it returns the position else it returns -1. [GFGTABS] JavaScript let str = "GFG\t@_123_$"; let regex = /\t/; let match = str.search(regex); if (match == -1) { console.log("No tab character pres
      1 min read

    • JavaScript RegExp \s Metacharacter
      The \s metacharacter in JavaScript regular expressions matches any whitespace character. This includes spaces, tabs, form feeds, line breaks, and other whitespace characters as defined in Unicode. [GFGTABS] JavaScript let regex = /\s/; let str1 = "Hello World"; let str2 = "HelloWorld
      2 min read

    • JavaScript RegExp \r Metacharacter
      The \r metacharacter in JavaScript regular expressions matches a carriage return character. A carriage return is a special control character (\r) with the ASCII code 13, often used to represent the end of a line in text files created on older operating systems (e.g., Windows uses \r\n for line break
      2 min read

    • JavaScript | RegExp \uxxxx Metacharacter
      The RegExp \uxxxx Metacharacter in JavaScript is used to find the unicode character specified by a hexadecimal number xxxx. If match is found it returns the word else it returns NULL. Syntax: /\uxxxx/ or new RegExp("\\uxxxx") Syntax with modifiers: /\uxxxx/g or new RegExp("\\uxxxx", "g") Example 1:
      2 min read

    • JavaScript RegExp \W Metacharacter
      The \W metacharacter in JavaScript regular expressions matches any character that is not a word character. A word character is defined as: Any alphanumeric character (a-z, A-Z, 0-9)The underscore (_)Essentially, \W matches anything that is not a letter, digit, or underscore. [GFGTABS] JavaScript let
      2 min read

    • JavaScript RegExp \w Metacharacter
      The \w metacharacter in JavaScript regular expressions matches any word character. A word character is defined as: Any alphanumeric character (letters a-z, A-Z, numbers 0-9)The underscore character (_)It does not match spaces, punctuation, or other non-alphanumeric characters. [GFGTABS] JavaScript l
      2 min read

    • JavaScript | RegExp \xxx Metacharacter
      The RegExp \xxx Metacharacter in JavaScript is used to find the character specified by an octal number xxx. If the match is found it returns the character else it returns NULL. Syntax: /\xxx/ or new RegExp("\\xxx") Syntax with modifiers: /\xxx/g or new RegExp("\\xxx", "g") Example 1: This example re
      2 min read

    • JavaScript RegExp \0 Metacharacter
      The RegExp \0 Metacharacter in JavaScript is used to find the NULL character. If it is found it returns the position else it returns -1. [GFGTABS] JavaScript let str = "Geeksfo\0rGeeks@_123_$"; let regex = /\0/; let match = str.search(regex); if (match == -1) { console.log("No Null ch
      2 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences