Check if a string is empty in JavaScript
Question:
How to check if a string is empty in JavaScript? Answer:
let str = ' ';
if ((str ?? '').trim().length === 0) {
console.log("The string is empty");
}
Description:
In JavaScript to check if a variable is an empty string is a bit tricky. You need to take into account special cases like what if the value is null or undefined or the string contains whitespace characters. So a generic solution you can use a helper function like this:
function isEmpty(str) {
if (typeof (str ?? '') === 'string' && (str ?? '').trim().length === 0) {
return true;
}
return false;
}
This code handles boolean and numeric values as not empty.
Reference:
JavaScript trim reference
Share "How to check if a string is empty in JavaScript?"
Related snippets:
- Declare existing global variable in TypeScript
- Check if number is odd or even in JavaScript
- Convert Fahrenheit to Celsius in JavaScript
- Remove double quotes from a string in JavaScript
- Get class name of an object in JavaScript
- Convert milliseconds to minutes and seconds
- Check if an array contains a value
- Append an array to another in JavaScript
- Create HTML element with attributes in JavaScript
- Check if a value is a number in JavaScript
- Check if date is valid in JavaScript
- Check if a string is empty in JavaScript
- Check if string contains a substring in JavaScript
- Get element by ID in React
- Set the required attribute in JavaScript
- Get the first element of an array in JavaScript
- Convert Map values to array in JavaScript
- Escape quotes in JavaScript
- Get elements by data attribute in JavaScript
- Access JavaScript object property with space
- Add class to multiple elements in JavaScript
- Add class to element if it does not already exists with JavaScript
- Add CSS class to body with JavaScript
- Add class to parent element in JavaScript
- Access JavaScript object property with hyphen
- Add new Key - Value pair to an object in JavaScript
Tags:
check, test, string, empty, null, undefined, javascript Technical term:
Check if a string is empty in JavaScript