To check if a JavaScript string is empty or contains only spaces, trim the content and check if the string is empty:
var str=' ';
if (str.trim() === "") {
// Do something, the string is empty or contains only spaces
}
To check if a JavaScript string is empty or contains only spaces, you can use one of the following approaches. Here's how you can do it:
trim()
and ComparisonThe trim()
method removes all whitespace from the beginning and end of a string. If the trimmed string is empty, it means the original string contained only spaces (or was empty).
function isEmptyOrSpaces(str) {
return str.trim() === "";
}
// Examples
console.log(isEmptyOrSpaces("")); // true
console.log(isEmptyOrSpaces(" ")); // true
console.log(isEmptyOrSpaces("Hello")); // false
console.log(isEmptyOrSpaces(" Hello ")); // false
A regular expression can match strings that contain only spaces or are empty.
function isEmptyOrSpaces(str) {
return /^[\s]*$/.test(str);
}
// Examples
console.log(isEmptyOrSpaces("")); // true
console.log(isEmptyOrSpaces(" ")); // true
console.log(isEmptyOrSpaces("Hello")); // false
console.log(isEmptyOrSpaces(" Hello ")); // false
If you also want to handle cases where the input is null
or undefined
, you can extend the logic:
function isEmptyOrSpaces(str) {
return !str || str.trim() === "";
}
// Examples
console.log(isEmptyOrSpaces(null)); // true
console.log(isEmptyOrSpaces(undefined)); // true
console.log(isEmptyOrSpaces("")); // true
console.log(isEmptyOrSpaces(" ")); // true
console.log(isEmptyOrSpaces("Hello")); // false
trim()
-based approach is simple and covers most common cases.!str
ensures null
or undefined
are considered "empty."