Skip to content
Home » How to Check if a String is Empty in JavaScript

How to Check if a String is Empty in JavaScript

In this tutorial let’s learn about How to Check if a String is Empty in JavaScript. Follow the any of the below methods to get a detail knowledge and code snippets are also given.

Using === Operator to Check if a String is Empty in JavaScript

We’ll use the === operator to see if the string is empty. If the string is empty, it will return “Empty String,” otherwise it will return “Not Empty String.” The comparison str === “” will only return true if the value’s datatype is a string and it is not empty, otherwise it will return false, as shown in the following example:

Code Example :

function checking(str)
{
// === operator
    if (str === "")
    {
	    console.log("Empty String")
	}
	else{
	    console.log("Not Empty String")
	}
}

// function call with empty string
checking("")

// function call with content string
checking("SimilarGeeks")

Output :

Empty String
Not Empty String

Check if a String is Empty using length in JavaScript

Here’s another method to test for a JavaScript empty string. We know the string is empty if the length is 0.

Code Example :

function checking(str)
{
	return (!str || str.length === 0 );
}

console.log(checking(""))
console.log(checking("SimilarGeeks"))

Output :

true
false

Check if a String is Empty using replace() Method in JavaScript

It ensures that the string isn’t just a bunch of empty spaces when we’re replacing the spaces.

Code Example :

function checking(str)
{
if(str.replace(/\s/g,"") == ""){
	console.log("Empty String")
}
else
{
	console.log("Not Empty String")
}
}

checking("  ")
checking("SimilarGeeks")

Output :

Empty String
Not Empty String

Conclusion

In this tutorial we learnt different ways to check whether the given string is an empty string or not. With the help of those JavaScript methods the task is done successfully.

Similar Posts:

Remove the First Character From String in JavaScript
How to Convert String to Lower Case using JavaScript