User Guide
Working with characters in strings 211
The length property
Every string has a length property, which is equal to the number of characters in the string:
var str:String = "macromedia";
trace(str.length); // 10
An empty string and a null string both have a length of 0, as the following example shows:
var str1:String = new String();
trace(str1.length); // 0
str2:String = '';
trace(str2.length); // 0
Working with characters in strings
Every character in a string has an index position in the string (an integer). The index position
of the first character is 0. For example, in the following string, the character
y is in position 0
and the character
w is in position 5:
"yellow"
You can examine individual characters in various positions in a string using the charAt()
method and the
charCodeAt() method, as in this example:
var str:String = "hello world!";
for (var:i = 0; i < str.length; i++)
{
trace(str.charAt(i) + " - " + str.charCodeAt(i));
}
When you run this code, the following output is produced:
h - 104
e - 101
l - 108
l - 108
o - 111
- 32
w - 119
o - 111
r - 114
l - 108
d - 100
! - 33