Skip to content

JavaScript check if string is empty or whitespace

  • by

Learn how to check if a string is empty or contains only whitespace characters in JavaScript. Explore two different approaches: using a regular expression and the test() method.

const str = "your string here";
const isEmptyOrWhitespace = /^\s*$/.test(str);

Or

if (/\S/.test(myString)) {
    // string is not empty and not just whitespace
}

Using the trim() method to remove leading and trailing whitespace and then check the length of the resulting string will not work.

JavaScript check if string is empty or whitespace example

Simple example code.

<!DOCTYPE html>
<html>
  <body>    
    <script>
    const str1 = "   "; 
    const str2 = "hello world";

    // Using regular expression and test() method
    const res1 = /^\s*$/.test(str1);
    const res2 = /^\s*$/.test(str2);

    console.log(res1); 
    console.log(res2);

    // Using trim() method and checking length
    const t1 = str1.trim().length > 0;
    const t2 = str2.trim().length > 0;

    console.log(t1);
    console.log(t2); 

    </script>
  </body>
</html>

Output:

JavaScript check if string is empty or whitespace

Use a regular expression and the test() method.

const str = "   "; // string with only whitespace characters
const isEmptyOrWhitespace = /^\s*$/.test(str);

if (isEmptyOrWhitespace) {
  console.log("String is empty or contains only whitespace");
} else {
  console.log("String is not empty and contains non-whitespace characters");
}

In this example, the regular expression /^\s*$/ matches any string that starts with zero or more whitespace characters (\s*) and ends immediately ($). The test() method returns true if the regular expression matches the string, and false otherwise.

if the string is null or undefined, you should check for that separately before using the regular expression, like this:

const str = null; // or undefined
const isEmptyOrWhitespace = str === null || str === undefined || /^\s*$/.test(str);

if (isEmptyOrWhitespace) {
  console.log("String is empty or contains only whitespace");
} else {
  console.log("String is not empty and contains non-whitespace characters");
}

Comment if you have any doubts or suggestions on this Js string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading