How to Check empty/undefined/null String in JavaScript?
Empty strings contain no characters, while null strings have no value assigned. Checking for an empty, undefined, or null string in JavaScript involves verifying if the string is falsy or has a length of zero. Here are different approaches to check a string is empty or not.
1. Using === Operator
Using === operator we will check the string is empty or not. If empty then it will return “Empty String” and if the string is not empty it will return “Not Empty String”.
Syntax
if (str === "") {
console.log("Empty String")
} else {
console.log("Not Empty String")
}
// Function to check string is empty or not
function checking(str){
// Checking the string using === operator
if (str === "") {
console.log("Empty String")
}
else {
console.log("Not Empty String")
}
}
// Checking for empty string
checking("");
checking("GeeksforGeeks");
Output
Empty String Not Empty String
2. Using length and ! Operator
This approach uses length property to get the length of string and ! operator. and by using ! operator we will check string is empty or not.
// Function to check string is empty or not
function checking(str) {
return (!str || str.length === 0 );
}
console.log(checking(""));
console.log(checking("GeeksforGeeks"));
Output
true false
3. Using replace() Method
This approach uses replace() Method. It will ensure that the string is not just a group of empty spaces where we are doing replacement on the spaces.
// function to check string is empty or not
function checking(str) {
if(str.replace(/\s/g,"") == "") {
console.log("Empty String")
}
else{
console.log("Not Empty String")
}
}
checking(" ");
checking("Hello Javascript");
Output
Empty String Not Empty String