Harsha
Harsha

Reputation: 239

regex dont match if it is an empty string

Currently, I am using /^[a-zA-Z.+-. ']+$/ regex to validate incoming strings.

When the incoming string is empty or only contains whitespace, I would like the code to throw an error.

How can I check for empty string using regex? I found some solutions but none are helpful.

Upvotes: 5

Views: 12092

Answers (3)

Starfish
Starfish

Reputation: 3574

To check for empty or whitespace-only strings you can use this regex: /^\s*$/

Example:

function IsEmptyOrWhiteSpace(str) {
    return (str.match(/^\s*$/) || []).length > 0;
}

var str1 = "";
var str2 = " ";
var str3 = "a b";

console.log(IsEmptyOrWhiteSpace(str1)); // true
console.log(IsEmptyOrWhiteSpace(str2)); // true
console.log(IsEmptyOrWhiteSpace(str3)); // false

Upvotes: 1

Kiran Shahi
Kiran Shahi

Reputation: 7980

Check if the string is empty or not using the following regex:

/^ *$/

The regex above matches the start of the string (^), then any number of spaces (*), then the end of the string ($). If you would instead like to match ANY white space (tabs, etc.), you can use \s* instead of *, making the regex the following:

/^\s*$/

Upvotes: 4

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

You may use

/^(?! *$)[a-zA-Z.+ '-]+$/

Or - to match any whitespace

/^(?!\s*$)[a-zA-Z.+\s'-]+$/

The (?!\s*$) negative lookahead will fail the match if the string is empty or only contains whitespace.

Pattern details

  • ^ - start of string
  • (?!\s*$) - no empty string or whitespaces only in the string
  • [a-zA-Z.+\s'-]+ - 1 or more letters, ., +, whitespace, ' or - chars
  • $ - end of string.

Note that actually, you may also use (?!\s+) lookahead here, since your pattern does not match an empty string due to the + quantifier at the end.

Upvotes: 4

Related Questions