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
This question is related to
javascript
jquery
regex
If one only cares about whitespace at the beginning and end of the string (but not in the middle), then another option is to use String.trim():
" your string contents ".trim();
// => "your string contents"
This is my solution
var error=0;
var test = [" ", " "];
if(test[0].match(/^\s*$/g)) {
$("#output").html("MATCH!");
error+=1;
} else {
$("#output").html("no_match");
}
Had similar problem, was looking for white spaces in a string, solution:
To search for 1 space:
var regex = /^.+\s.+$/ ;
example: "user last_name"
To search for multiple spaces:
var regex = /^.+\s.+$/g ;
example: "user last name"
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
}
Source: Stackoverflow.com