- Javascript: Check if string is empty (6 ways)
- Javascript check if string is empty using === operator
- Javascript check if string is empty using length and ! operator
- Frequently Asked:
- Javascript check if string is empty or has only white spaces
- Javascript check if string is valid using typecasting
- Javascript check if string is empty using replace
- Javascript check if string is empty using case statement
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- Javascript check string is not empty
- # Check if a String is Empty in JavaScript
- # Handling strings that only contain spaces
- # Checking if a string isn’t empty
- # Checking if a string isn’t empty or contains only whitespace
- # Checking if a value is falsy
- # Checking if a value is an empty string, undefined or null
- # Checking if a value is NOT an empty string, undefined or null
- # Checking if a value is empty using lodash
- # Additional Resources
Javascript: Check if string is empty (6 ways)
This article will see how to check if a string is empty using different methods and various examples.
Table of Contents:-
Javascript check if string is empty using === operator
In the below example, a function is used to determine if the string is empty or not. If blank, the function will print The string is empty else, it will print The string is not empty.
function isEmptyCheck(string1) < if (string1 === "") < console.log("The string is empty") >else < console.log("The string is not empty") >> isEmptyCheck("") isEmptyCheck("Hello Javascript")
The string is empty The string is not empty
Javascript check if string is empty using length and ! operator
In the below example, a function will determine if the string is empty or not. If empty, the function returns true else it will return false .
Frequently Asked:
function isEmptyFunction(_string) < return (!_string || _string.length === 0 ); >console.log(isEmptyFunction("")) console.log(isEmptyFunction("Hello Javascript"))
Javascript check if string is empty or has only white spaces
In the below example, the function will determine if the string is empty or not or has only white spaces. The function would return true if the string passed as an argument is empty or has only white spaces. The function returns false for other inputs.
function isEmptyFunction2(_string1) < return (_string1.length === 0 || !_string1.trim()); >; console.log(isEmptyFunction2("Hello Javascript")) console.log(isEmptyFunction2("")) console.log(isEmptyFunction2(" "))
Important Note: The function will return an error “trim is not a function” if the input argument passed is not a string.
Javascript check if string is valid using typecasting
In the below example, the function will determine if the string is valid or not. The function will typecast the variable to Boolean. The function prints The string is improper when null, undefined, 0, 000, “”, false are input arguments and The string is proper when a string, “0” and whitespace are input arguments.
function isImproperStringCheck(_stringInput) < if (Boolean(_stringInput)) < console.log("The string is proper") //false for null, undefined, 0, 000, "", false. >else < console.log("The string is improper") //true for string "0" and whitespace " ". >> isImproperStringCheck("") isImproperStringCheck(" ") isImproperStringCheck("Hello Javascript") isImproperStringCheck(0) isImproperStringCheck("0")
The string is improper The string is proper The string is proper The string is improper The string is proper
Javascript check if string is empty using replace
In the below example, the function will determine if the string is empty or not. The function will print The string is blank in case the string is empty or has only white spaces. Else will print The string is not blank
function isEmptyCheck(_string) < if(_string.replace(/\s/g,"") == "")< console.log("The string is blank") >else < console.log("The string is not blank") >> isEmptyCheck("") isEmptyCheck(" ") isEmptyCheck("Hello Javascript")
The string is blank The string is blank The string is not blank
Important Note: The function will return an error “replace is not a function” if the input argument passed is not a string.
Javascript check if string is empty using case statement
In the below example, the function will check different cases and print String is empty/null/undefined/0 if the input argument is empty, null, undefined, false, or 0 else will print String input is valid .
function check_empty(_string) < switch (_string) < case "": case null: case false: case 0: case typeof(_string) == "undefined": return "String is empty/null/undefined/0"; default: return "String input is valid"; >> console.log(check_empty(null)) console.log(check_empty("Hello Javascript")) console.log(check_empty(0)) console.log(check_empty(7) ) console.log(check_empty(""))
String is empty/null/undefined/0 String input is valid String is empty/null/undefined/0 String input is valid String is empty/null/undefined/0
We hope this article helped you to check if a string is empty in javascript. Good Luck .
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Javascript check string is not empty
Last updated: Feb 15, 2023
Reading time · 5 min
# Check if a String is Empty in JavaScript
Use the length property on the string to check if it is empty.
If the string’s length is equal to 0 , then it’s empty, otherwise, it isn’t empty.
Copied!const str = ''; if (typeof str === 'string' && str.length === 0) // 👇️ this runs console.log('The string is empty'); > else console.log('The string is NOT empty') >
The String.length property returns the number of characters in the string.
Copied!console.log(''.length); // 👉️ 0 console.log('a'.length); // 👉️ 1 console.log('ab'.length); // 👉️ 2
If accessing the string’s length property returns 0 , then the string is empty.
If you have to do this often, define a reusable function.
Copied!function isEmpty(string) return typeof string === 'string' && string.length === 0; > console.log(isEmpty('')); // 👉️ true console.log(isEmpty('a')); // 👉️ false console.log(isEmpty('ab')); // 👉️ false if (isEmpty('')) // 👇️ this runs console.log('The string is empty'); > else console.log('The string is NOT empty'); >
The function takes a string as a parameter and returns true if the string is empty and false otherwise.
# Handling strings that only contain spaces
If you also consider an empty string one that contains only spaces, use the String.trim() method before checking if the string is empty.
Copied!const str = ' '; if (typeof str === 'string' && str.trim().length === 0) // 👇️ this runs console.log('The string is empty'); > else console.log('THe string is NOT empty'); >
The String.trim() method removes the leading and trailing whitespace from a string and returns a new string, without modifying the original string.
Copied!const str = ' '; console.dir(str.trim()); // 👉️ "" console.dir(str.length); // 👉️ 8 console.dir(str.trim().length); // 👉️ 0
The trim() method removes all whitespace characters including spaces, tabs and newlines.
You can also use the optional chaining (?.) operator if you need to handle null and undefined values.
Copied!const str = ' '; if (str?.trim()) console.log('The string is NOT empty'); > else // 👇️ this runs console.log('The string is empty'); >
The optional chaining (?.) operator short-circuits and returns undefined if the value to the left is nullish ( null or undefined ).
This handles a scenario where the str variable stores an undefined value.
Copied!const str = undefined; if (str?.trim()) console.log('The string is NOT empty'); > else // 👇️ this runs console.log('The string is empty'); >
Instead of getting an error for trying to call the trim() method on an undefined value, the call short-circuits returning undefined because we used the optional chaining (?.) operator.
# Checking if a string isn’t empty
Use the value in an if statement to check if it is truthy.
Copied!const str = 'bobbyhadz.com'; if (str) // if this code block runs // str is NOT "", undefined, null, 0, false, NaN console.log('The value is truthy'); > else console.log( 'The value is undefined, null 0, false, NaN or empty string', ); >
The code in the if block wouldn’t run if the str variable is set to an empty string, undefined , null , 0 , false or NaN .
All other values are truthy.
You can also check that the value isn’t equal to an empty string.
Copied!const str = ''; if (typeof str === 'string' && str !== '') console.log('The string is NOT empty'); > else // 👇️ this runs console.log('The string is empty'); >
We used the logical AND (&&) operator to chain 2 conditions. Both conditions have to be met for the if block to run.
- The first condition checks that the value is a string.
- The second checks that the string isn’t empty.
Checking that the value is a string is important because we shouldn’t compare an empty string to a value of a different type.
# Checking if a string isn’t empty or contains only whitespace
This approach wouldn’t work for a string that contains only spaces.
If you need to handle strings that contain only spaces, use the trim() method.
Copied!const str = ' '; if (typeof str === 'string' && str.trim() !== '') console.log('The string is NOT empty'); > else // 👇️ this runs console.log('The string is empty'); >
We first make sure that the str variable contains a string and then we call the String.trim() method.
If we try to call the trim method on a variable that is set to undefined or null , we’d get an error.
This is useful when you have to take user input and want to make sure the user didn’t just enter spaces to get around your validation.
# Checking if a value is falsy
If you need to check for a falsy value, use the logical NOT (!) operator.
Copied!const str = 'bobbyhadz.com'; if (!str) console.log( 'The value is undefined, null 0, false, NaN or empty string', ); > else // 👉️ str is NOT "", undefined, null, 0, false, NaN console.log('The string is truthy'); >
The if block is only run if the str variable stores a falsy value.
The falsy values in JavaScript are: false , 0 , empty string «» , null , undefined and NaN (not a number).
All other values are truthy.
# Checking if a value is an empty string, undefined or null
You can use the logical OR (||) operator if you want to explicitly check if a variable stores an empty string, undefined or null .
Copied!const str = ''; if (typeof str === undefined || str === null || str === '') // 👇️ this runs console.log('The value is undefined, null or empty string'); > else console.log( 'The value is NOT undefined, null or empty string', ); >
We used the logical OR (||) operator, so the if block is run if either condition is met.
The if block in the example runs if the str variable stores undefined , null or an empty string.
# Checking if a value is NOT an empty string, undefined or null
Conversely, you can use the logical AND (&&) operator to check if a variable doesn’t store an empty string, null or undefined .
Copied!const str = 'bobbyhadz.com'; if (typeof str !== undefined && str !== null && str !== '') // 👇️ this runs console.log( 'The value is NOT undefined, null or empty string', ); > else console.log('The value is undefined, null or empty string'); >
We used the logical AND (&&) operator, so for the if block to run, all conditions have to be met.
- The variable doesn’t store an undefined value.
- The variable doesn’t store a null value.
- The variable is not an empty string.
# Checking if a value is empty using lodash
If you use the lodash module, you can also use the isEmpty() method to check if a value is empty.
If you need to install lodash , run the following command.
Copied!# 👇️ initialize a package.json file npm init -y npm install lodash
You can now import and use the lodash.isEmpty method.
Copied!import _ from 'lodash'; console.log(_.isEmpty(null)); // 👉️ true console.log(_.isEmpty(undefined)); // 👉️ true console.log(_.isEmpty('')); // 👉️ true console.log(_.isEmpty([])); // 👉️ true console.log(_.isEmpty(>)); // 👉️ true console.log(_.isEmpty(true)); // 👉️ true console.log(_.isEmpty('abc')); // 👉️ false console.log(_.isEmpty(['a', 'b'])); // 👉️ false console.log(_.isEmpty(a: 'b'>)); // 👉️ false
The isEmpty method returns true if the value is an empty string, null , undefined , an empty object, collection, Map or Set .
Array-like objects, buffers and strings are considered empty if they have a length of 0 .
Similarly, Map and Set objects are considered empty if they have a size of 0 .
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.