JavaScript - check if string contains only digits

6 points
Created by:

In this article, we would like to show you how to check if the string contains only digits in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

let value = '123';

let result = /^\d+$/.test(value);

console.log(result);  // true


Practical example

In this example, we present how to check if the string contains only digits using regex.


  • \d - stands for "digit" and matches any digit character (0-9),
  • ^ - matches the beginning of the string,
  • + - matches one or more of the preceding token (in our case one or more \d),
  • $ - matches the end of the string.

Runnable example:

// ONLINE-RUNNER:browser;

let number = '123';

let text1 = 'A12';
let text2 = '1A2';
let text3 = '12A';

let empty = '';

let result1 = /^\d+$/.test(number);  // true
let result2 = /^\d+$/.test(text1);   // false
let result3 = /^\d+$/.test(text2);   // false
let result4 = /^\d+$/.test(text3);   // false
let result5 = /^\d+$/.test(empty);   // false

console.log(result1);  // true
console.log(result2);  // false
console.log(result3);  // false
console.log(result4);  // false
console.log(result5);  // false

See also

  1. JavaScript - check if character is digit


  1. RegExp.prototype.test() - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - check if string contains only digits

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂