- Using the typeof Operator and length Property:
- Check if the variable is a string and its length is 0
let str = "";
if (typeof str === "string" && str.length === 0) {
console.log("The string is empty");
}
- Using the length Property Directly:
- Directly check if the string's length is 0
let str = "";
if (str.length === 0) {
console.log("The string is empty");
}
- Using the trim Method:
- Remove leading and trailing whitespace characters before checking for emptiness:
let str = " ";
if (str.trim().length === 0) {
console.log("The string is empty");
}
- Comparing with an Empty String:
let myStr = "";
if (myStr === "") {
console.log("This is an empty String!");
}
- Checking for Null Directly
let myStr = null;
if (myStr === null) {
console.log("This is a null String!");
}
- Combining Null and Empty Checks:
let myStr = null;
if (myStr === null || myStr.trim() === "") {
console.log("This is an empty String!");
}
- By using replace
- It will ensure that the string is not just a group of empty spaces where we are doing replacement on the spaces
let str = "";
if(str.replace(/\s/g,"") == ""){
console.log("Empty String")
}
- By Converting String to Boolean
let str = undefined;
if (Boolean(str) == false) {
console.log("str is either null, empty, or undefined")
}
- Using strict equality operator
if (str === "" || str === null || str === undefined) {
// string is not valid
} else {
// string is valid
}
- Creating a custom function that checks for null, undefined, empty strings,
and strings that contain only whitespace characters:
function isEmpty(str) {
// check if the string is null or undefined
if (str === null || str === undefined) {
return true;
}
// check if the string is an empty string or contains only whitespace characters
return str.trim().length === 0;
}