Reputation: 2043
In the jquery below should there be a closing paretheses ")" before the "dot" in:
".test($
..."?
(/^\s*$/.test($(this).val()))
$(document).ready(function () {
$('#userlogin').css('color', '#cccccc').val('LOGINNAME');
$('#userlogin').blur(function () {
if (/^\s*$/.test($(this).val())) {
$(this).val('LOGINNAME');
$(this).css('color', '#cccccc');
$(this).valid();
}
}).focus(function () {
if ($(this).val() === 'LOGINNAME') {
$(this).val('');
$(this).css('color', '#000000');
}
});
If not, why not? That code looks a little weird to me.
Upvotes: 2
Views: 99
Reputation: 268512
/^\s*$/.test( $(this).val() )
The first part is a regular expression - not a string or anything else. As such, it begins and ends with deliminters /
and /
.
Using .match
is sometimes more legible as it doesn't appear to have some strange unbound item floating around in the source:
$(this).val().match(/^\s*$/);
This particular expression, broken down, reads like this:
/^ // Beginning of String
\s* // Space, zero or more times
$/ // End of String
So it will test positive if there are zero or more spaces, from start to finish, and nothing else.
Upvotes: 2
Reputation: 25475
The code is fine. If you think its unreadable why not create the regex first
var regex = /^\s*$/;
if(regex.test($(this).val())
...
Upvotes: 2
Reputation:
/^\s*$/
is a regular expression literal and it has a test method which is being called. The brackets are from the if condition which is bigger.
Since javascript is fully object oriented even literals can have methods.
Upvotes: 2
Reputation: 318808
The code is correct:
/^\s*$/ // create a regex
.test( // call the test method on it
$(this) // create a jquery object
.val() // call the val method on it
)
However, the value could be cached: var val = $(this).val();
.
Then the line might be less confusing to you: /yourregex/.test(val)
Upvotes: 4