- 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 Empty String – Checking Null or Empty in JS
- What’s the Difference Between Null and Empty?
- How to Check for Empty or Null in JavaScript
- How to Check for an Empty String in JavaScript with the length Property
- How to Check for an Empty String in JavaScript by String Comparison
- How to Check for Null in JavaScript
- How to Check for a Null or Empty String in JavaScript
- Conclusion
- How to Check if a String is Empty in JavaScript
- Tip
- How to Check if a String is Empty, null, or undefined
- 2. Comparing the Length of the String with 0
- Every Crazy Thing JavaScript Does
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 Empty String – Checking Null or Empty in JS
Joel Olawanle
There are a number of reasons why you might need to check if a string is empty or not. One of the most important reasons is when you’re retrieving data from a database, API, or input field.
In this article, you will learn how to check if a sting is empty or null in JavaScript. We will see many examples and methods you can use so that you can understand them and decide which one to use and when.
What’s the Difference Between Null and Empty?
Before we begin, you need to understand what the terms Null and Empty mean, and understand that they are not synonymous.
For example, if we declare a variable and assign it an empty string, and then declare another variable and assign it the Null value, we can tell them apart by looking at their datatype:
let myStr1 = ""; let myStr2 = null; console.log(typeof myStr1); // "string" console.log(typeof myStr2); // "object"
Looking at the code above, we can see that the compiler/computer interprets each value differently. So when it comes time to check, we must pass conditions for both types of values because we as humans frequently refer to null as empty.
How to Check for Empty or Null in JavaScript
We now know that an empty string is one that contains no characters. It is very simple to check if a string is empty. We can use two major methods that are somewhat similar because we will use the strict equality operator ( == ).
How to Check for an Empty String in JavaScript with the length Property
In this first method, we will check for the length of the string by adding the length property. We’ll check if the length is equal to 0 . If it’s equal to zero, it means that the string is empty, as we can see below:
let myStr = ""; if (myStr.length === 0)
The above will return this:
But this approach unfortunately might not work in all situations. For example, if we have a string that has white spaces as seen below:
let myStr = " "; if (myStr.length === 0) < console.log("This is an empty string!"); >else
"This is NOT an empty string!"
We can easily fix this error by first removing the white spaces using the trim() method before checking for the length of such string to see if it’s empty as seen below:
let myStr = " "; if (myStr.trim().length === 0) < console.log("This is an empty string!"); >else
This will now return the following:
Note: If the value is null, this will throw an error because the length property does not work for null.
To fix this, we can add an argument that checks if the value’s type is a string and skips this check if it is not:
let myStr = null; if (typeof myStr === "string" && myStr.trim().length === 0)
How to Check for an Empty String in JavaScript by String Comparison
Another way to check if a string is empty is by comparing the string to an empty string.
As with the previous method, 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
Just as we did for the length method, 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() === "")
How to Check for Null in JavaScript
So far, we’ve seen how to check if a string is empty using the length and comparison methods.
Now, let’s see how to check if it’s null , and then check for both. To check for null , we simply compare that variable to null itself as follows:
let myStr = null; if (myStr === null)
How to Check for a Null or Empty String in JavaScript
At this point we have learned how to check for an empty string and also if a variable is set is null. Let’s now check to for both this way:
let myStr = null; if (myStr === null || myStr.trim() === "") < console.log("This is an empty string!"); >else
Conclusion
In this article, we learned how to check for an empty string or null and why they are not the same thing.
How to Check if a String is Empty in JavaScript
To check if a string is empty in JavaScript, we can compare the string with an empty string ( » ) in an if statement.
function checkIfEmpty(str) < if (str === '') < console.log('String is empty'); >else < console.log('String is NOT empty'); >> const str1 = 'not empty'; const str2 = ''; // empty checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty
To treat a string containing only whitespace as empty, call the trim() method on the string before comparing it with an empty string.
function checkIfEmpty(str) < if (str.trim() === '') < console.log('String is empty'); >else < console.log('String is NOT empty'); >> const str1 = 'not empty'; const str2 = ''; // empty const str3 = ' '; // contains only whitespace checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty checkIfEmpty(str3); // outputs: String is empty
The String trim() method removes all whitespace from the beginning and end of a string and returns a new string, without modifying the original.
const str1 = ' bread '; const str2 = ' milk tea '; console.log(str1.trim()); // 'bread' console.log(str2.trim()); // 'milk tea'
Tip
Trimming a string when validating required fields in a form helps ensure that the user entered actual data instead of just whitespace.
How to Check if a String is Empty, null, or undefined
Depending on your scenario, you might want to consider that the string could be a nullish value ( null or undefined ). To check for this, use the string if statement directly, like this:
function checkIfEmpty(str) < if (str) < console.log('String is NOT empty'); >else < console.log('String is empty'); >> const str1 = 'not empty'; const str2 = ''; // empty const str3 = null; const str4 = undefined; checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty checkIfEmpty(str3); // outputs: String is empty checkIfEmpty(str4); // outputs: String is empty
If the string is nullish or empty, it will be coerced to false in the if statement. Otherwise, it will be coerced to true .
To remove all whitespace and also check for a nullish value, use the optional chaining operator ( ?. ) to call the trim() method on the string before using it in an if statement.
function checkIfEmpty(str) < if (str?.trim()) < console.log('String is NOT empty'); >else < console.log('String is empty'); >> const str1 = 'not empty'; const str2 = ''; // empty const str3 = null; const str4 = undefined; const str5 = ' '; // contains only whitespace checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty checkIfEmpty(str3); // outputs: String is empty checkIfEmpty(str4); // outputs: String is empty checkIfEmpty(str5); // outputs: String is empty
The optional chaining operator lets us call the trim() method on a null or undefined string without causing an error. Instead, it prevents the method call and returns undefined .
const str1 = null; const str2 = undefined; console.log(str1?.trim()); // undefined console.log(str2?.trim()); // undefined
2. Comparing the Length of the String with 0
Alternatively, we can access the length property of a string and compare its value with 0 to check if the string is empty.
function checkIfEmpty(str) < if (str.length === 0) < console.log('String is empty'); >else < console.log('String is NOT empty'); >> const str1 = 'not empty'; const str2 = ''; // empty checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty
To check for strings containing only whitespace with this approach, we would also call the trim() method before comparing the length of the trimmed string with 0 .
function checkIfEmpty(str) < if (str.trim().length === 0) < console.log('String is empty'); >else < console.log('String is NOT empty'); >> const str1 = 'not empty'; const str2 = ''; // empty const str3 = ' '; // contains only whitespace checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty checkIfEmpty(str3); // outputs: String is empty
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.