JavaScript Length; You will often find it necessary to count characters and words in strings, particularly with strings from form submissions. For example, you might need to count the number of characters in a password to ensure that a user selects a password with a minimum number of characters.
Or, you might have a Web page that allows users to submit classified ads that cannot exceed a maximum number of characters. The String class contains a single property, the JavaScript Length property, which returns the number of characters in a string. To return the total number of characters in a string, you append the JavaScript Length property of the String class to a literal string, variable, or object containing text.
For example, the following code uses the JavaScript Length property to count the number of characters in a variable named country. The document.write() statement prints “The country name contains 18 characters.”
var country = "Kingdom of Morocco"; document.write("<p>The country name contains " + country.length + " characters.</p>"); The following example of JavaScript Length uses a regular text string. It writes the length of the string variable onto the page. <body> <script type="text/javascript"> var myname="John"; document.write("The name has "+myname.length+" characters."); </script> </body>
Notice how the name of the variable is used like an object name here. This is how to get JavaScript to create a temporary String object to use the property. The script writes the result to the page. Because the name has four characters, the JavaScript Length property has a value of 4 here.
The JavaScript Length property will be quite useful when you want to break strings apart to get information or make changes to them, especially if the viewer enters the string and you don’t know its length beforehand. This property reflects the number of characters, including blanks, which it contains. Here are a few examples:
var str1 = "abc" var str2 = "a b c" var str3 = "\"abc\"" document.write(str1.length + "<BR>") document.write(str2.length + "<BR>") document.write(str3.length) The output of this script is: 3 5 5
The index of a string’s last character is equal to its length (number of characters) minus one. The string’s length is the index of the nonexistent character following the string’s last character.