whisher wrote:
Hi.
I'm taking my first steps on regex I set up
this simple function to check if a form field is empty
or with only space.
var onlySpaceRegexp = /^\s*$/;
Pre-initialising a regexp is handy if you are going to use it more than
once, but for one-of cases, there isn't much point other than for style
or convention.
function isEmpty(val)
{
if (onlySpaceRegexp.test(val) || val == "")
The second test is completely covered by the first (which matches
strings consisting of only zero or more spaces), and therefore is
redundant.
{
return true;
}
else
There is no need for an 'else' after a conditional return, though maybe
is makes maintenance easier.
{
return false;
}
}
alert(isEmpty(""));//TRUE
alert(isEmpty(" "));//TRUE
alert(isEmpty(" v "));//FALSE
I'm wandering is it the best way ?
You might consider one of the following:
function isEmpty(val){
return /^\s*$/.test(val);
}
function isEmpty(val){
return !/\S/.test(val);
}
You might want to handle cases where val isn't a string, the following
is a start but what should be returned if val isn't a string?
function isEmpty(val){
if (typeof val == 'string'){
return /^\s*$/.test(val);
}
// val isn't as string, what now?
}
--
Rob