Find the Length of a String using jQuery

Leave a Comment

There are times when you want to know how many characters are in a string. Strings have a length property that gives you just this kind of information. Add a period after the name of the variable, followed by length to get the number of characters in the string: name.length.

For example, assume you have a form with a text field. The field has the ID of password.

To make sure the password has the proper number of characters, you could use a conditional statement to test the password’s length like this:
var password = $('#password').val();
if (password.length <= 6) {
alert('That password is too short.');
} else if (password.length > 15) {
alert('That password is too long.');
}

0 comments:

Post a Comment