EN
JavaScript - check if string contains only digits
6
points
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.
Where:
\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