Regular expression to match numbers only in JavaScript?

In this tutorial, we will learn regular expressions to match numbers only in JavaScript.

Data validation is essential for web applications. We often need to ensure users provide correct input ? for example, phone numbers should contain only digits, or credit card fields should accept numbers only.

Regular expressions provide a powerful way to validate and extract numeric data from strings. They use patterns to match specific character types and return the matched results.

Understanding Regular Expression Patterns

A regular expression consists of a pattern and optional modifiers. For matching numbers, we use:

  • \d - Matches any single digit (0-9)
  • \d+ - Matches one or more consecutive digits
  • ^[0-9]+$ - Matches strings containing only digits from start to end
  • g - Global modifier to find all matches

Syntax

// Regular expression literal syntax
var pattern = /\d+/g;

// RegExp constructor syntax
var pattern = new RegExp('^[0-9]+$');

// Using with string methods
'your string here'.match(pattern);
pattern.test('your string here');

Method 1: Extracting All Numbers from Text

Use /\d+/g to find and extract all numeric sequences from a string:

<html>
<body>
   <h3>Extract Numbers from Text</h3>
   <label for="textInput">Enter text with numbers:</label>
   <input type="text" id="textInput" placeholder="e.g., I have 5 apples and 10 oranges" />
   <button onclick="extractNumbers()">Extract Numbers</button>
   <div id="result"></div>
   
   <script>
      function extractNumbers() {
         var input = document.getElementById("textInput").value;
         var numberPattern = /\d+/g;
         var numbers = input.match(numberPattern);
         
         var resultDiv = document.getElementById("result");
         if (numbers) {
            resultDiv.innerHTML = "<p>Numbers found: " + numbers.join(", ") + "</p>";
         } else {
            resultDiv.innerHTML = "<p>No numbers found in the text.</p>";
         }
      }
   </script>
</body>
</html>

Method 2: Validating Numbers-Only Input

Use ^[0-9]+$ to verify that a string contains only digits:

<html>
<body>
   <h3>Validate Phone Number (Numbers Only)</h3>
   <label for="phoneInput">Enter phone number:</label>
   <input type="text" id="phoneInput" placeholder="1234567890" />
   <button onclick="validatePhone()">Validate</button>
   <div id="validation"></div>
   
   <script>
      function validatePhone() {
         var phone = document.getElementById("phoneInput").value;
         var numbersOnly = new RegExp('^[0-9]+$');
         var validationDiv = document.getElementById("validation");
         
         // Clear previous result
         validationDiv.innerHTML = '';
         
         if (numbersOnly.test(phone) && phone.length === 10) {
            validationDiv.innerHTML = "<span style='color: green;'>? Valid phone number</span>";
         } else if (!numbersOnly.test(phone)) {
            validationDiv.innerHTML = "<span style='color: red;'>? Phone number must contain only digits</span>";
         } else {
            validationDiv.innerHTML = "<span style='color: red;'>? Phone number must be 10 digits</span>";
         }
      }
   </script>
</body>
</html>

Comparison of Methods

Pattern Purpose Returns Use Case
/\d+/g Extract numbers Array of matches Finding all numbers in text
^[0-9]+$ Validate numbers-only Boolean (with test()) Form validation

Common Use Cases

  • Form Validation: Ensuring phone numbers, IDs, or codes contain only digits
  • Data Processing: Extracting numeric values from mixed content
  • Input Filtering: Real-time validation as users type
  • Data Cleaning: Removing non-numeric characters from datasets

Conclusion

Regular expressions provide efficient number validation in JavaScript. Use /\d+/g to extract numbers from text and ^[0-9]+$ to validate numbers-only input. Choose the appropriate pattern based on whether you need extraction or validation.

Updated on: 2026-03-15T23:18:59+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements