Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for empty string or white space

I am trying to detect if a user enter whitespace in a textbox:

 var regex = "^\s+$" ;   if($("#siren").val().match(regex)) {      echo($("#siren").val());      error+=1;     $("#siren").addClass("error");     $(".div-error").append("- Champ Siren/Siret ne doit pas etre vide<br/>");  } 

if($("#siren").val().match(regex)) is supposed to match whitespace string, however, it doesn' t seems to work, what am I doing wrong ?

Thanks for your helps

like image 293
dtjmsy Avatar asked Oct 01 '13 16:10

dtjmsy


People also ask

What is empty space in regex?

\s is the regex character for whitespace. It matches spaces, new lines, carriage returns, and tabs.

Is empty string a whitespace?

First you should know the difference between empty string and a white space. The length of a white ' ' space is 1 . An empty string '' will have a length zero.

How do you find a space in a string in regex?

Spaces can be found simply by putting a space character in your regex. Whitespace can be found with \s . If you want to find whitespace between words, use the \b word boundary marker.

Does empty regex match everything?

An empty regular expression matches everything.


2 Answers

The \ (backslash) in the .match call is not properly escaped. It would be easier to use a regex literal though. Either will work:

var regex = "^\\s+$"; var regex = /^\s+$/; 

Also note that + will require at least one space. You may want to use *.

like image 119
Explosion Pills Avatar answered Oct 12 '22 13:10

Explosion Pills


If you are looking for empty string in addition to whitespace you meed to use * rather than +

var regex = /^\s*$/ ;                 ^ 
like image 31
asantaballa Avatar answered Oct 12 '22 13:10

asantaballa