EN
TypeScript - check if string contains only digits
0 points
In this article, we would like to show you how to check if the string contains only digits in TypeScript.
Quick solution:
xxxxxxxxxx
1
const value: string = '123';
2
3
const result: boolean = /^\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
// ONLINE-RUNNER:browser;
2
3
const number: string = '123';
4
5
const text1: string = 'A12';
6
const text2: string = '1A2';
7
const text3: string = '12A';
8
9
const empty: string = '';
10
11
const result1: boolean = /^\d+$/.test(number); // true
12
const result2: boolean = /^\d+$/.test(text1); // false
13
const result3: boolean = /^\d+$/.test(text2); // false
14
const result4: boolean = /^\d+$/.test(text3); // false
15
const result5: boolean = /^\d+$/.test(empty); // false
16
17
console.log(result1); // true
18
console.log(result2); // false
19
console.log(result3); // false
20
console.log(result4); // false
21
console.log(result5); // false
Output:
xxxxxxxxxx
1
true
2
false
3
false
4
false
5
false