Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

How to Check for an Empty String in JavaScript by String Comparison

// checking if a string is empty is by comparing the string to an empty string.

// For example:

let myStr = "";

if (myStr === "") {
  console.log("This is an empty string!");
}

// if we have white spaces, this will not read the string as empty.
// So we must first use the trim() method to remove all forms of whitespace:

let myStr = "   ";

if (myStr.trim() === "") {
  console.log("This is an empty string!");
} else {
  console.log("This is NOT an empty string!");
}

// we can also check for the type of the value so that this will only run when
// the value is a string:

let myStr = null;

if (typeof myStr === "string" && myStr.trim() === "") {
  console.log("This is an empty string!");
}
Source by www.freecodecamp.org #
 
PREVIOUS NEXT
Tagged: #How #Check #Empty #String #JavaScript #String #Comparison
ADD COMMENT
Topic
Name
6+3 =