Check if a string contains only whitespace in typescript
To check if a string contains only whitespace in typescript, you can use the trim()
method with the if...else
statement it will go in else
if the string contains blank spaces.
// β
Check if a string contains only whitespace Using `trim()` method
(" ".trim()) ? "String contain character" : "String contain only spaces"; // ποΈ 'String contain only spaces'
Today, I’m going to show you How do I check if a string contains only whitespace in typescript, as above mentioned here, I’m going to use the trim()
method with the if...else
statement it will print in the else
statement if the string contains only blank spaces.
Let’s start today’s tutorial how do you check if a string contains only whitespace in typescript?
Here, I have taken example two string one have only empty space and one have some words.
const str1: string = " ";
const str2: string = " Infint bility ";
// β
Check str1 contain only whitespace
if(str1.trim()){
console.log("str1 contain character");
} else {
console.log("str1 contain only space");
}
// β
Check str2 contain only whitespace
if(str2.trim()){
console.log("str2 contain character");
} else {
console.log("str2 contain only space");
}
// β
Output
// ποΈ 'str1 contain only space'
// ποΈ 'str2 contain character'
I hope it helps you, All the best π.