javascript regex check if string is empty

How to Use JavaScript Regex to Check if a String is Empty

If you are a web developer, you have probably come across the need to check if a string is empty. This can be done using JavaScript and Regex. Here's how:

Method 1: Using Regex.test()

The easiest way to check if a string is empty using Regex is to use the test() method. Here's how:


const str = "";
const regex = /^\s*$/;

if (regex.test(str)) {
  console.log("The string is empty.");
} else {
  console.log("The string is not empty.");
}
  • const str = ""; - This sets the value of the string we want to check to an empty string.
  • const regex = /^\s*$/; - This creates a regular expression that matches any string that consists of zero or more whitespace characters.
  • if (regex.test(str)) { /* ... */ } - This checks if the regular expression matches the empty string.

If the regular expression matches the empty string, then the console will print "The string is empty." Otherwise, it will print "The string is not empty."

Method 2: Using String.trim()

Another way to check if a string is empty is to use the trim() method, which removes whitespace from both ends of a string. Here's how:


const str = "";
if (str.trim() === "") {
  console.log("The string is empty.");
} else {
  console.log("The string is not empty.");
}
  • const str = ""; - This sets the value of the string we want to check to an empty string.
  • if (str.trim() === "") { /* ... */ } - This checks if the trimmed string is equal to an empty string.

If the trimmed string is equal to an empty string, then the console will print "The string is empty." Otherwise, it will print "The string is not empty."

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe