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


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


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

var regex = /^\s*$/ ;
                ^

If you're using jQuery, you have .trim().

if ($("#siren").val().trim() == "") {
  // it's empty
}