Skip to content
the poor coder

javascript regex check if string is empty

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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."

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC