Skip to content

Instantly share code, notes, and snippets.

@AhmadHRai
Created April 20, 2024 11:57
Show Gist options
  • Save AhmadHRai/1bf6c6b57f5821ac12da7d8ae5f261aa to your computer and use it in GitHub Desktop.
Save AhmadHRai/1bf6c6b57f5821ac12da7d8ae5f261aa to your computer and use it in GitHub Desktop.
Ways to check if a string is null, empty or equals an empty string ('')
  1. 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");
}
  1. 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");
}
  1. 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");
}
  1. Comparing with an Empty String:
let myStr = "";
if (myStr === "") {
  console.log("This is an empty String!");
}
  1. Checking for Null Directly
let myStr = null;
if (myStr === null) {
  console.log("This is a null String!");
}
  1. Combining Null and Empty Checks:
let myStr = null;
if (myStr === null || myStr.trim() === "") {
  console.log("This is an empty String!");
}
  1. 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") 
} 
  1. By Converting String to Boolean
let str = undefined;
if (Boolean(str) == false) {
    console.log("str is either null, empty, or undefined") 
}
  1. Using strict equality operator
if (str === "" || str === null || str === undefined) {
   // string is not valid
} else {
   // string is valid
}
  1. 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;

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment