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:
const text: string = 'Example text.';
if (text.match(/\s/)) {
console.log('The string contains space(s).');
}
Practical example
In this example, we use match()
method to check if the text
string contains any spaces.
const regex: RegExp = /\s/;
const text: string = 'Example text.';
if (text.match(regex)) {
console.log('The string contains space(s).');
}
Output:
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
.
Alternative solution
In this section, we use regex.test(text)
instead of text.match(regex)
to check if the text
string contains spaces.
const regex: RegExp = /\s/;
const text: string = 'Example text.';
if (regex.test(text)) {
console.log('The string contains space(s).');
}
Output:
The string contains space(s).
Note:
The
test()
method returnstrue
if there is a match between theregex
and thetext
string. Otherwise it returnsfalse
.