user
How to check if a JavaScript string is empty or contains only spaces?
alphonsio

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:

1. Using trim() and Comparison

The 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

2. Using Regular Expressions

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

3. Handling Null or Undefined (Optional)

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

Key Differences Between Approaches

  • The trim()-based approach is simple and covers most common cases.
  • Regular expressions are more versatile if you need additional matching logic.
  • Adding !str ensures null or undefined are considered "empty."