ÄúµÄλÖãºÑ°ÃÎÍøÊ×Ò³£¾±à³ÌÀÖÔ°£¾JavaScript£¾Javascript Tutorial
Javascript Tutorial

Javascript - Intro
Javascript - Syntax
Javascript - Location
Javascript - External
Javascript - Operators
Javascript - Variables
Javascript - Functions
Javascript - Events
Javascript - Statements
Javascript - If
Javascript - Else If
Javascript - While
Javascript - For Loop
Javascript - Comments
Javascript - Array
Javascript - Alert
Javascript - Confirm
Javascript - Prompt
Javascript - Print
Javascript - Redirect
Javascript - Pop Up
Javascript - Date
Javascript - Form
Javascript - Void 0

Javascript String

Javascript - Strings
Javascript - Length
Javascript - Split
Javascript - Search
Javascript - Replace
Javascript - indexOf
Javascript - Compare

Javascript Advanced

Javascript - getElementById
Javascript - innerHTML

Javascript String Length

Advanced scripters will often need to know how long a Javascript string is. For example, if a webdeveloper was creating a submission form that required the username to be no longer than 20 characters, then she would need to check the length of the string before allowing the user to submit data.

String Length Property

The length property returns the number of characters that are in a string, using an integer. Below is the basic code for accessing this property.

Javscript Code:

<script type="text/javascript">
var myString = "123456";

var length = myString.length;

document.write("The string is this long: " + length);

// Same thing, but using the property inside the write function
document.write("<br />The string is this long: " + myString.length);

</script>

Display:

Change the String? Length Might Change

If you were to reference the length property after concatenating (adding) some characters to the string, then the property will reflect these changes. Think of this as a reminder to only check the length of the string after you are sure it isn't going to be changed.

Javscript Code:

<script type="text/javascript">
var myString = "123456";
document.write("The string is this long: " + myString.length);

myString = myString + "7890";
document.write("<br />The string is now this long: " + myString.length);

</script>

Display: