How to check empty/undefined/null string in JavaScript?
Last Updated :
12 Jan, 2023
If we want to check any string either it is filled or empty we can use Javascript for such purpose for example : form validation.
Example :
html
< script >
function checkempty(form) {
if (form.name.value == null ||
form.name.value == undefined ||
form.name.value.length == 0) {
alert("Name cannot be empty\n");
return false;
} else {
alert("Your response has been recorded\n");
return true;
}
}
</ script >
< form onsubmit = "return checkempty(form1)" action = "#" method = "post" name = "form1" >
< label >Enter your name</ label >
< br >
< input type = "string" placeholder = "Enter name" name = "name" />
< br >
< br >
< label >Enter Email</ label >
< br >
< input type = "" placeholder = "Enter email" name = "email" />
< br >
< br >
< label >Enter password</ label >
< br >
< input type = "password" placeholder = "Enter password " name = "password1" />
< br >
< br >
< label >Confirm password</ label >
< br >
< input type = "password" placeholder = "Enter password " name = "password2" />
< br >
< br >
< input type = "submit" value = "submit" />
< br >
</ form >
|
Output: If the name is empty.
How to check empty/undefined/null string in JavaScript?
Simplified with 3 Different Methods
Method 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”
Javascript
function checking(str){
if (str === "" ) {
console.log( "Empty String" )
}
else {
console.log( "Not Empty String" )
}
}
checking( "" )
checking( "GeeksforGeeks" )
|
Output:
Empty String
Not Empty String
Method 2: By using the length and ! operator
This function will check the length of the string also by using ! operator we will check string is empty or not.
Javascript
function checking(str) {
return (!str || str.length === 0 );
}
console.log(checking( "" ))
console.log(checking( "GeeksforGeeks" ))
|
Output:
true
false
Method 3: 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.
Javascript
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...