Problem Statement
How do you check if a string is empty or contains only whitespace in JavaScript?
Explanation
Checking for empty or whitespace-only strings is common in form validation and data processing.
Empty string check:
Compare length property to zero. Or compare directly to empty string with triple equals. Or use logical NOT for falsy check, but be careful as it also catches undefined and null.
Whitespace-only check:
Use trim method and check if result is empty. This removes all leading and trailing whitespace. If trimmed string is empty, original contained only whitespace.
Common validation patterns:
Check if string exists and has content. Check if string is not just spaces. Validate user input before processing. Provide user feedback for invalid input.
Edge cases to consider:
Null and undefined are not empty strings. Zero is not an empty string. Tab and newline characters are whitespace. Empty array converted to string is empty string.
Best practices:
Always trim user input before validation. Check for both null or undefined and empty. Provide clear error messages. Use helper functions for reusability.
String validation is essential for building robust applications that handle user input correctly.
Code Solution
SolutionRead Only
// CHECK IF STRING IS EMPTY
// Method 1: Check length
function isEmpty(str) {
return str.length === 0;
}
console.log(isEmpty('')); // true
console.log(isEmpty('hello')); // false
// Method 2: Direct comparison
function isEmpty2(str) {
return str === '';
}
// Method 3: Falsy check (careful!)
if (!str) {
// This catches '', undefined, null
console.log('Empty or falsy');
}
// CHECK IF STRING IS EMPTY OR WHITESPACE
// Method 1: Trim and check (best)
function isEmptyOrWhitespace(str) {
return str.trim().length === 0;
}
console.log(isEmptyOrWhitespace('')); // true
console.log(isEmptyOrWhitespace(' ')); // true
console.log(isEmptyOrWhitespace('\t\n')); // true
console.log(isEmptyOrWhitespace('hello')); // false
// Method 2: Regex
function isEmptyOrWhitespace2(str) {
return /^\s*$/.test(str);
}
// HANDLE NULL/UNDEFINED
function isNullOrEmpty(str) {
return !str || str.trim().length === 0;
}
console.log(isNullOrEmpty(null)); // true
console.log(isNullOrEmpty(undefined)); // true
console.log(isNullOrEmpty('')); // true
console.log(isNullOrEmpty(' ')); // true
console.log(isNullOrEmpty('hello')); // false
// FORM VALIDATION EXAMPLE
function validateForm(formData) {
const errors = [];
// Check username
if (!formData.username || formData.username.trim().length === 0) {
errors.push('Username is required');
}
// Check email
if (!formData.email || formData.email.trim().length === 0) {
errors.push('Email is required');
}
// Check if string has minimum length
if (formData.password && formData.password.trim().length < 8) {
errors.push('Password must be at least 8 characters');
}
return errors;
}
const errors = validateForm({
username: ' ',
email: '',
password: 'short'
});
console.log(errors);
// ['Username is required', 'Email is required', 'Password must be...']
// REUSABLE VALIDATION HELPERS
const StringUtils = {
isEmpty: (str) => !str || str.length === 0,
isBlank: (str) => !str || str.trim().length === 0,
hasContent: (str) => str && str.trim().length > 0,
hasMinLength: (str, min) => str && str.trim().length >= min,
isNotEmpty: (str) => str && str.length > 0
};
// Usage
const input = ' hello ';
console.log(StringUtils.isEmpty(input)); // false
console.log(StringUtils.isBlank(input)); // false
console.log(StringUtils.hasContent(input)); // true
// EDGE CASES
console.log(isEmpty(null)); // TypeError (cannot read length)
console.log(isEmpty(undefined)); // TypeError
console.log(isEmpty(0)); // TypeError
// Safe check
function safeIsEmpty(str) {
return typeof str === 'string' && str.length === 0;
}
console.log(safeIsEmpty(null)); // false
console.log(safeIsEmpty('')); // true