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:
xxxxxxxxxx
1
let value = '123';
2
3
let result = /^\d+$/.test(value);
4
5
console.log(result); // true
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:
xxxxxxxxxx
1
let number = '123';
2
3
let text1 = 'A12';
4
let text2 = '1A2';
5
let text3 = '12A';
6
7
let empty = '';
8
9
10
let result1 = /^\d+$/.test(number); // true
11
let result2 = /^\d+$/.test(text1); // false
12
let result3 = /^\d+$/.test(text2); // false
13
let result4 = /^\d+$/.test(text3); // false
14
let result5 = /^\d+$/.test(empty); // false
15
16
console.log(result1); // true
17
console.log(result2); // false
18
console.log(result3); // false
19
console.log(result4); // false
20
console.log(result5); // false