There are a number of reasons why you might need to check if a string is empty or not. One of the most important reasons is when you're retrieving data from a database, API, or input field.
In this article, you will learn how to check if a sting is empty or not in JavaScript. We have 3 methods you can use.
Method 1: Check the string using length
Use the length property to check if a string is empty, e.g. if (str.length === 0) {}. If the string's length is equal to 0, then it's empty, otherwise it isn't empty.
Code:
const str = 'Hello';
if (typeof str === 'string' && str.length === 0) {
console.log('String is empty');
} else {
console.log(str, "is the string")
console.log('String is NOT empty')
}
Output:
Method 2: Check the String using trim()
The trim() method removes the leading and trailing spaces from a string. If the string contains only spaces, trim() returns an empty string.
If you consider an empty string one that contains only spaces, use the trim() method to remove any leading or trailing whitespace before checking if it's empty.
Code:
const str = ' Welcome ';
if (typeof str === 'string' && str.trim().length === 0) {
console.log('String is empty');
} else {
console.log(str, "is the string")
console.log('String is NOT empty');
}
Output:
Method 3: Check the String using If else Statement
Using if else statement you can check if the string is empty or not. But if you use only if statement, and if the string is empty, the code will not run. And also if the string has some string, then you will get your result. See the below code where we have used both if else statement.
Code:
const str = ' Welcome sir';
if (str) {
console.log(str, "is the String")
console.log("String is truthy")
}
else
{
console.log("String is empty")
}
Output:
The Tech Platform
Comments