1 2 3
const str = '';
'' with the appropriate string variable or literal you want to check.
2. Use the
length property of a string returns the number of characters in the string. To check if a string is empty, you can compare its
1 2 3 4
const isEmpty = str.length === 0; console.log(isEmpty); // Output: true
In this example, the
isEmpty variable is
true because the
length of the empty string is
3. Use the
trim() method removes leading and trailing whitespace from a string. By using it in combination with the
length property, you can check if a string is empty or contains only whitespace characters.
1 2 3 4
const isEmpty = str.trim().length === 0; console.log(isEmpty); // Output: true
In this example, any leading or trailing whitespace in the string will be removed before checking its
4. Use regular expressions and the
If you want to check if a string contains only whitespace characters, you can use a regular expression and the
test() method to match against whitespace patterns.
1 2 3 4
const isEmpty = /^\s*$/.test(str); console.log(isEmpty); // Output: true
In this example, the regular expression
/^\s*$/ matches a string that contains only whitespace characters or is empty. The
test() method returns
true if the string matches the regular expression.
Choose the method that best fits your requirements and the specific context in which you need to check if a string is empty. The
length property is recommended for most cases as it provides a simple and straightforward way to check if a string has no characters. The other methods offer alternative approaches if you need to account for whitespace characters or have more specific requirements.