JavaScript - Empty String Check


String is a data type, which we can use to save the data present in text format. It is a sequence of characters inside the double or single quotes.

Sometimes we need to check whether the string is empty or not. In JavaScript, we can check the empty string using the following methods.

Using the length property

It's really simple and most common way to check the empty string. All we have to do is check the length of the string using the length property of the string. If the length of the string is 0, then it is an empty string. If length is 1 or more than 1 then string is not empty.

Syntax

Below is the syntax given to check the empty string using the length property.

if(string_name.length === 0){
   // string is empty
}

Example

Below is the example code given, that shows how to use the length property to check the empty string.

<html>
<body>
<script>
var str = '';
if(str.length === 0){
   document.write('String is empty');
}
</script>
</body>
</html>

Following is the output of the above program −

String is empty

Using the trim() method

The string.trim() method allows us to remove the space from the start of the string. After moving the space, we can check that if the strings length is zero, the string can be either empty, null, or undefined.

Syntax

Below is the syntax given to check the empty string using the trim() method.

if(string_name.trim() === ''){
   // string is empty
}

Example

Below is the example code given, that shows how to use the trim() method to check the empty string.

<html>
<body>
<script>
var str = ' ';
if(str.trim() === ''){
   document.write('String is empty');
}
</script>
</body>
</html>

Following is the output of the above program −

String is empty

So, we have seen how to check the empty string in JavaScript using the length property and trim() method.

Advertisements