EN
TypeScript - check if string contains spaces
0 points
In this article, we would like to show you how to check if string contains spaces in TypeScript.
Quick solution:
xxxxxxxxxx
1
const text: string = 'Example text.';
2
3
if (text.match(/\s/)) {
4
console.log('The string contains space(s).');
5
}
In this example, we use match()
method to check if the text
string contains any spaces.
xxxxxxxxxx
1
const regex: RegExp = /\s/;
2
const text: string = 'Example text.';
3
4
if (text.match(regex)) {
5
console.log('The string contains space(s).');
6
}
Output:
xxxxxxxxxx
1
The string contains space(s).
Note:
The
match()
method used with/g
flag returns all results matching the complete regular expression (regex
). If nothing matches returnsnull
.
In this section, we use regex.test(text)
instead of text.match(regex)
to check if the text
string contains spaces.
xxxxxxxxxx
1
const regex: RegExp = /\s/;
2
const text: string = 'Example text.';
3
4
if (regex.test(text)) {
5
console.log('The string contains space(s).');
6
}
Output:
xxxxxxxxxx
1
The string contains space(s).
Note:
The
test()
method returnstrue
if there is a match between theregex
and thetext
string. Otherwise it returnsfalse
.