Adobe® Flex® 4 Language Reference
Hide Packages and Classes List |  Packages  |  Classes  |  Index  |  Appendixes
__Global__ 
String 
PackageTop Level
Classpublic final class String
InheritanceString Inheritance Object

Runtime Versions: Flash Player 9, AIR 1.0

The String class is a data type that represents a string of characters. The String class provides methods and properties that let you manipulate primitive string value types. You can convert the value of any object into a String data type object using the String() function.

All the methods of the String class, except for concat(), fromCharCode(), slice(), and substr(), are generic, which means the methods call toString() before performing their operations, and you can use these methods with other non-String objects.

Because all string indexes are zero-based, the index of the last character for any string x is x.length - 1.

You can call any of the methods of the String class whether you use the constructor method new String() to create a new string variable or simply assign a string literal value. Unlike previous versions of ActionScript, it makes no difference whether you use the constructor, the global function, or simply assign a string literal value. The following lines of code are equivalent:

 var str:String = new String("foo");
 var str:String = "foo";
 var str:String = String("foo");

When setting a string variable to undefined, Adobe® Flash® Player coerces undefined to null. So, the statement:

 var s:String = undefined;
sets the value to null instead of undefined. Use the String() function if you need to use undefined.

View the examples

See also



Public Properties
 PropertyDefined By
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  length : int
[read-only] An integer specifying the number of characters in the specified String object.
String
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
Public Methods
 MethodDefined By
  
Creates a new String object initialized to the specified string.
String
  
charAt(index:Number = 0):String
Returns the character in the position specified by the index parameter.
String
  
Returns the numeric Unicode character code of the character at the specified index.
String
  
Appends the supplied arguments to the end of the String object, converting them to strings if necessary, and returns the resulting string.
String
  
[static] Returns a string comprising the characters represented by the Unicode character codes in the parameters.
String
 Inherited
Indicates whether an object has a specified property defined.
Object
  
indexOf(val:String, startIndex:Number = 0):int
Searches the string and returns the position of the first occurrence of val found at or after startIndex within the calling string.
String
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
  
lastIndexOf(val:String, startIndex:Number = 0x7FFFFFFF):int
Searches the string from right to left and returns the index of the last occurrence of val found before startIndex.
String
  
localeCompare(other:String, ... values):int
Compares the sort order of two or more strings and returns the result of the comparison as an integer.
String
  
match(pattern:*):Array
Matches the specifed pattern against the string.
String
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
  
replace(pattern:*, repl:Object):String
Matches the specifed pattern against the string and returns a new string in which the first match of pattern is replaced with the content specified by repl.
String
  
search(pattern:*):int
Searches for the specifed pattern and returns the index of the first matching substring.
String
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
  
slice(startIndex:Number = 0, endIndex:Number = 0x7fffffff):String
Returns a string that includes the startIndex character and all characters up to, but not including, the endIndex character.
String
  
split(delimiter:*, limit:Number = 0x7fffffff):Array
Splits a String object into an array of substrings by dividing it wherever the specified delimiter parameter occurs.
String
  
substr(startIndex:Number = 0, len:Number = 0x7fffffff):String
Returns a substring consisting of the characters that start at the specified startIndex and with a length specified by len.
String
  
substring(startIndex:Number = 0, endIndex:Number = 0x7fffffff):String
Returns a string consisting of the character specified by startIndex and all characters up to endIndex - 1.
String
  
Returns a copy of this string, with all uppercase characters converted to lowercase.
String
 Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
  
Returns a copy of this string, with all lowercase characters converted to uppercase.
String
  
Returns a copy of this string, with all uppercase characters converted to lowercase.
String
 Inherited
Returns the string representation of the specified object.
Object
  
Returns a copy of this string, with all lowercase characters converted to uppercase.
String
  
Returns the primitive value of a String instance.
String
Property Detail

length

property
length:int  [read-only]

Runtime Versions: Flash Player 9, AIR 1.0

An integer specifying the number of characters in the specified String object.

Because all string indexes are zero-based, the index of the last character for any string x is x.length - 1.



Implementation
    public function get length():int
Constructor Detail

String

()Constructor
public function String(val:String)

Runtime Versions: Flash Player 9, AIR 1.0

Creates a new String object initialized to the specified string.

Note: Because string literals use less overhead than String objects and are generally easier to use, you should use string literals instead of the String class unless you have a good reason to use a String object rather than a string literal.

Parameters
val:String — The initial value of the new String object.
Method Detail

charAt

()method
AS3 function charAt(index:Number = 0):String

Runtime Versions: Flash Player 9, AIR 1.0

Returns the character in the position specified by the index parameter. If index is not a number from 0 to string.length - 1, an empty string is returned.

This method is similar to String.charCodeAt() except that the returned value is a character, not a 16-bit integer character code.

Parameters

index:Number (default = 0) — An integer specifying the position of a character in the string. The first character is indicated by 0, and the last character is indicated by my_str.length - 1.

Returns
String — The character at the specified index. Or an empty string if the specified index is outside the range of this string's indices.

See also

charCodeAt

()method 
AS3 function charCodeAt(index:Number = 0):Number

Runtime Versions: Flash Player 9, AIR 1.0

Returns the numeric Unicode character code of the character at the specified index. If index is not a number from 0 to string.length - 1, NaN is returned.

This method is similar to String.charAt() except that the returned value is a 16-bit integer character code, not the actual character.

Parameters

index:Number (default = 0) — An integer that specifies the position of a character in the string. The first character is indicated by 0, and the last character is indicated by my_str.length - 1.

Returns
Number — The Unicode character code of the character at the specified index. Or NaN if the index is outside the range of this string's indices.

Unicode values are defined in the Unicode Character Database specification.

See also

concat

()method 
AS3 function concat(... args):String

Runtime Versions: Flash Player 9, AIR 1.0

Appends the supplied arguments to the end of the String object, converting them to strings if necessary, and returns the resulting string. The original value of the source String object remains unchanged.

Parameters

... args — Zero or more values to be concatenated.

Returns
String — A new string consisting of this string concatenated with the specified parameters.

fromCharCode

()method 
AS3 static function fromCharCode(... charCodes):String

Runtime Versions: Flash Player 9, AIR 1.0

Returns a string comprising the characters represented by the Unicode character codes in the parameters.

Parameters

... charCodes — A series of decimal integers that represent Unicode values.

Unicode values are defined in the Unicode Character Database specification.

Returns
String — The string value of the specified Unicode character codes.

indexOf

()method 
AS3 function indexOf(val:String, startIndex:Number = 0):int

Runtime Versions: Flash Player 9, AIR 1.0

Searches the string and returns the position of the first occurrence of val found at or after startIndex within the calling string. This index is zero-based, meaning that the first character in a string is considered to be at index 0--not index 1. If val is not found, the method returns -1.

Parameters

val:String — The substring for which to search.
 
startIndex:Number (default = 0) — An optional integer specifying the starting index of the search.

Returns
int — The index of the first occurrence of the specified substring or -1.

See also

lastIndexOf

()method 
AS3 function lastIndexOf(val:String, startIndex:Number = 0x7FFFFFFF):int

Runtime Versions: Flash Player 9, AIR 1.0

Searches the string from right to left and returns the index of the last occurrence of val found before startIndex. The index is zero-based, meaning that the first character is at index 0, and the last is at string.length - 1. If val is not found, the method returns -1.

Parameters

val:String — The string for which to search.
 
startIndex:Number (default = 0x7FFFFFFF) — An optional integer specifying the starting index from which to search for val. The default is the maximum value allowed for an index. If startIndex is not specified, the search starts at the last item in the string.

Returns
int — The position of the last occurrence of the specified substring or -1 if not found.

See also

localeCompare

()method 
AS3 function localeCompare(other:String, ... values):int

Runtime Versions: AIR 1.0, Flash Player 9

Compares the sort order of two or more strings and returns the result of the comparison as an integer. While this method is intended to handle the comparison in a locale-specific way, the ActionScript 3.0 implementation does not produce a different result from other string comparisons such as the equality (==) or inequality (!=) operators. If the strings are equivalent, the return value is 0. If the original string value precedes the string value specified by other, the return value is a negative integer, the absolute value of which represents the number of characters that separates the two string values. If the original string value comes after other, the return value is a positive integer, the absolute value of which represents the number of characters that separates the two string values.

Parameters

other:String — A string value to compare.
 
... values — Optional set of more strings to compare.

Returns
int — The value 0 if the strings are equal. Otherwise, a negative integer if the original string precedes the string argument and a positive integer if the string argument precedes the original string. In both cases the absolute value of the number represents the difference between the two strings.

match

()method 
AS3 function match(pattern:*):Array

Runtime Versions: AIR 1.0, Flash Player 9

Matches the specifed pattern against the string.

Parameters

pattern:* — The pattern to match, which can be any type of object, but it is typically either a string or a regular expression. If the pattern is not a regular expression or a string, then the method converts it to a string before executing.

Returns
Array — An array of strings consisting of all substrings in the string that match the specified pattern.

If pattern is a regular expression, in order to return an array with more than one matching substring, the g (global) flag must be set in the regular expression:

  • If the g (global) flag is not set, the return array will contain no more than one match, and the lastIndex property of the regular expression remains unchanged.
  • If the g (global) flag is set, the method starts the search at the beginning of the string (index position 0). If a matching substring is an empty string (which can occur with a regular expression such as /x*/), the method adds that empty string to the array of matches, and then continues searching at the next index position. The lastIndex property of the regular expression is set to 0 after the method completes.

If no match is found, the method returns null. If you pass no value (or an undefined value) as the pattern parameter, the method returns null.

See also

replace

()method 
AS3 function replace(pattern:*, repl:Object):String

Runtime Versions: AIR 1.0, Flash Player 9

Matches the specifed pattern against the string and returns a new string in which the first match of pattern is replaced with the content specified by repl. The pattern parameter can be a string or a regular expression. The repl parameter can be a string or a function; if it is a function, the string returned by the function is inserted in place of the match. The original string is not modified.

In the following example, only the first instance of "sh" (case-sensitive) is replaced:

    var myPattern:RegExp = /sh/;  
    var str:String = "She sells seashells by the seashore.";
    trace(str.replace(myPattern, "sch"));  
       // She sells seaschells by the seashore.

In the following example, all instances of "sh" (case-sensitive) are replaced because the g (global) flag is set in the regular expression:

    var myPattern:RegExp = /sh/g;  
    var str:String = "She sells seashells by the seashore.";
    trace(str.replace(myPattern, "sch"));  
       // She sells seaschells by the seaschore.

In the following example, all instance of "sh" are replaced because the g (global) flag is set in the regular expression and the matches are not case-sensitive because the i (ignoreCase) flag is set:

    var myPattern:RegExp = /sh/gi;  
    var str:String = "She sells seashells by the seashore.";
    trace(str.replace(myPattern, "sch"));  
       // sche sells seaschells by the seaschore.

Parameters

pattern:* — The pattern to match, which can be any type of object, but it is typically either a string or a regular expression. If you specify a pattern parameter that is any object other than a string or a regular expression, the toString() method is applied to the parameter and the replace() method executes using the resulting string as the pattern.
 
repl:Object — Typically, the string that is inserted in place of the matching content. However, you can also specify a function as this parameter. If you specify a function, the string returned by the function is inserted in place of the matching content.

When you specify a string as the repl parameter and specify a regular expression as the pattern parameter, you can use the following special $ replacement codes in the repl string:

$ Code Replacement Text
$$ $
$& The matched substring.
$` The portion of the string that precedes the matched substring. Note that this code uses the straight left single quote character (`), not the straight single quote character (') or the left curly single quote character (‘).
$' The portion of string that follows the matched substring. Note that this code uses the straight single quote character (').
$n The nth captured parenthetical group match, where n is a single digit 1-9 and $n is not followed by a decimal digit.
$nn The nnth captured parenthetical group match, where nn is a two-digit decimal number (01-99). If the nnth capture is undefined, the replacement text is an empty string.

For example, the following shows the use of the $2 and $1 replacement codes, which represent the first and second capturing group matched:

var str:String = "flip-flop";
    var pattern:RegExp = /(\w+)-(\w+)/g;
    trace(str.replace(pattern, "$2-$1")); // flop-flip

When you specify a function as the repl, the replace() method passes the following parameters to the function:

  • The matching portion of the string.
  • Any captured parenthetical group matches are provided as the next arguments. The number of arguments passed this way will vary depending on the number of parenthetical matches. You can determine the number of parenthetical matches by checking arguments.length - 3 within the function code.
  • The index position in the string where the match begins.
  • The complete string.

For example, consider the following:

    var str1:String = "abc12 def34";
    var pattern:RegExp = /([a-z]+)([0-9]+)/;
    var str2:String = str1.replace(pattern, replFN);
    trace (str2);   // 12abc 34def
    
    function replFN():String {
        return arguments[2] + arguments[1];
    }

The call to the replace() method uses a function as the repl parameter. The regular expression (/([a-z]([0-9]/g) is matched twice. The first time, the pattern matches the substring "abc12", and the following list of arguments is passed to the function:

    {"abc12", "abc", "12", 0, "abc12 def34"}

The second time, the pattern matches the substring "def23", and the following list of arguments is passed to the function:

    {"def34", "def", "34", 6, "abc123 def34"}

Returns
String — The resulting string. Note that the source string remains unchanged.

See also

search

()method 
AS3 function search(pattern:*):int

Runtime Versions: AIR 1.0, Flash Player 9

Searches for the specifed pattern and returns the index of the first matching substring. If there is no matching substring, the method returns -1.

Parameters

pattern:* — The pattern to match, which can be any type of object but is typically either a string or a regular expression.. If the pattern is not a regular expression or a string, then the method converts it to a string before executing. Note that if you specify a regular expression, the method ignores the global flag ("g") of the regular expression, and it ignores the lastIndex property of the regular expression (and leaves it unmodified). If you pass an undefined value (or no value), the method returns -1.

Returns
int — The index of the first matching substring, or -1 if there is no match. Note that the string is zero-indexed; the first character of the string is at index 0, the last is at string.length - 1.

See also

slice

()method 
AS3 function slice(startIndex:Number = 0, endIndex:Number = 0x7fffffff):String

Runtime Versions: Flash Player 9, AIR 1.0

Returns a string that includes the startIndex character and all characters up to, but not including, the endIndex character. The original String object is not modified. If the endIndex parameter is not specified, then the end of the substring is the end of the string. If the character indexed by startIndex is the same as or to the right of the character indexed by endIndex, the method returns an empty string.

Parameters

startIndex:Number (default = 0) — The zero-based index of the starting point for the slice. If startIndex is a negative number, the slice is created from right-to-left, where -1 is the last character.
 
endIndex:Number (default = 0x7fffffff) — An integer that is one greater than the index of the ending point for the slice. The character indexed by the endIndex parameter is not included in the extracted string. If endIndex is a negative number, the ending point is determined by counting back from the end of the string, where -1 is the last character. The default is the maximum value allowed for an index. If this parameter is omitted, String.length is used.

Returns
String — A substring based on the specified indices.

See also

split

()method 
AS3 function split(delimiter:*, limit:Number = 0x7fffffff):Array

Runtime Versions: Flash Player 9, AIR 1.0

Splits a String object into an array of substrings by dividing it wherever the specified delimiter parameter occurs.

If the delimiter parameter is a regular expression, only the first match at a given position of the string is considered, even if backtracking could find a nonempty substring match at that position. For example:

     var str:String = "ab";
     var results:Array = str.split(/a*?/); // results == ["","b"]
     
     results = str.split(/a*/); // results == ["","b"].)

If the delimiter parameter is a regular expression containing grouping parentheses, then each time the delimiter is matched, the results (including any undefined results) of the grouping parentheses are spliced into the output array. For example

     var str:String = "Thi5 is a tricky-66 example.";
     var re:RegExp = /(\d+)/;
     var results:Array = str.split(re);
         // results == ["Thi","5"," is a tricky-","66"," example."]

If the limit parameter is specified, then the returned array will have no more than the specified number of elements.

If the delimiter is an empty string, an empty regular expression, or a regular expression that can match an empty string, each single character in the string is output as an element in the array.

If the delimiter parameter is undefined, the entire string is placed into the first element of the returned array.

Parameters

delimiter:* — The pattern that specifies where to split this string. This can be any type of object but is typically either a string or a regular expression. If the delimiter is not a regular expression or string, then the method converts it to a string before executing.
 
limit:Number (default = 0x7fffffff) — The maximum number of items to place into the array. The default is the maximum value allowed.

Returns
Array — An array of substrings.

See also

substr

()method 
AS3 function substr(startIndex:Number = 0, len:Number = 0x7fffffff):String

Runtime Versions: Flash Player 9, AIR 1.0

Returns a substring consisting of the characters that start at the specified startIndex and with a length specified by len. The original string is unmodified.

Parameters

startIndex:Number (default = 0) — An integer that specified the index of the first character to be used to create the substring. If startIndex is a negative number, the starting index is determined from the end of the string, where -1 is the last character.
 
len:Number (default = 0x7fffffff) — The number of characters in the substring being created. The default value is the maximum value allowed. If len is not specified, the substring includes all the characters from startIndex to the end of the string.

Returns
String — A substring based on the specified parameters.

substring

()method 
AS3 function substring(startIndex:Number = 0, endIndex:Number = 0x7fffffff):String

Runtime Versions: Flash Player 9, AIR 1.0

Returns a string consisting of the character specified by startIndex and all characters up to endIndex - 1. If endIndex is not specified, String.length is used. If the value of startIndex equals the value of endIndex, the method returns an empty string. If the value of startIndex is greater than the value of endIndex, the parameters are automatically swapped before the function executes. The original string is unmodified.

Parameters

startIndex:Number (default = 0) — An integer specifying the index of the first character used to create the substring. Valid values for startIndex are 0 through String.length. If startIndex is a negative value, 0 is used.
 
endIndex:Number (default = 0x7fffffff) — An integer that is one greater than the index of the last character in the extracted substring. Valid values for endIndex are 0 through String.length. The character at endIndex is not included in the substring. The default is the maximum value allowed for an index. If this parameter is omitted, String.length is used. If this parameter is a negative value, 0 is used.

Returns
String — A substring based on the specified parameters.

toLocaleLowerCase

()method 
AS3 function toLocaleLowerCase():String

Runtime Versions: AIR 1.0, Flash Player 9

Returns a copy of this string, with all uppercase characters converted to lowercase. The original string is unmodified. While this method is intended to handle the conversion in a locale-specific way, the ActionScript 3.0 implementation does not produce a different result from the toLowerCase() method.

Returns
String — A copy of this string with all uppercase characters converted to lowercase.

See also

toLocaleUpperCase

()method 
AS3 function toLocaleUpperCase():String

Runtime Versions: Flash Player 9, AIR 1.0

Returns a copy of this string, with all lowercase characters converted to uppercase. The original string is unmodified. While this method is intended to handle the conversion in a locale-specific way, the ActionScript 3.0 implementation does not produce a different result from the toUpperCase() method.

Returns
String — A copy of this string with all lowercase characters converted to uppercase.

See also

toLowerCase

()method 
AS3 function toLowerCase():String

Runtime Versions: Flash Player 9, AIR 1.0

Returns a copy of this string, with all uppercase characters converted to lowercase. The original string is unmodified.

This method converts all characters (not simply A-Z) for which Unicode lowercase equivalents exist:

     var str:String = " JOSÉ BARÇA";
     trace(str.toLowerCase()); // josé barça

These case mappings are defined in the Unicode Character Database specification.

Returns
String — A copy of this string with all uppercase characters converted to lowercase.

See also

toUpperCase

()method 
AS3 function toUpperCase():String

Runtime Versions: Flash Player 9, AIR 1.0

Returns a copy of this string, with all lowercase characters converted to uppercase. The original string is unmodified.

This method converts all characters (not simply a-z) for which Unicode uppercase equivalents exist:

     var str:String = "José Barça";
     trace(str.toUpperCase()); // JOSÉ BARÇA

These case mappings are defined in the Unicode Character Database specification.

Returns
String — A copy of this string with all lowercase characters converted to uppercase.

See also

valueOf

()method 
AS3 function valueOf():String

Language Version: ActionScript 3.0
Runtime Versions: Flash Player 9, AIR 1.0

Returns the primitive value of a String instance. This method is designed to convert a String object into a primitive string value. Because Flash Player automatically calls valueOf() when necessary, you rarely need to explicitly call this method.

Returns
String — The value of the string.
StringExample.as

The following example uses the StringExample and StringHelper classes to show how various methods of the String class are used. This is accomplished using the following steps:
  1. The constructor for StringExample declares several local String instances, which are initialized with various strings and a new StringHelper object.
  2. The StringHelper class has the following methods:
    • replace(): calls the split() and join() methods of String to remove a substring of the string passed in with a new one.
    • trim(): calls both trimBack() and trimFront() using the strings passed in and returns the updated string.
    • trimFront():recursively removes all characters that match the char parameter, starting from the front of the string and working toward the end, until the first character in the string does not match char and returns the updated string.
    • trimBack(): recursively removes all characters that match the char parameter, starting from the end of the string and working backward, until the last character in the string does not match char and returns the updated string.
    • stringToCharacter(): returns the first character of the string passed to it.
  3. Three strings are then produced using the declared string variables with a call to the replace() method used to produce the second string and trim() to produce the third string.
package {
    import flash.display.Sprite;

    public class StringExample extends Sprite {
        public function StringExample() {
            var companyStr:String = new String("     Company X");
            var productStr:String = "Product Z Basic     ";
            var emptyStr:String = " ";
            var strHelper:StringHelper = new StringHelper();

            var companyProductStr:String = companyStr + emptyStr + productStr;
            trace("'" + companyProductStr + "'");    // '     Company X Product Z Basic     '

            companyProductStr = strHelper.replace(companyProductStr, "Basic", "Professional");
            trace("'" + companyProductStr + "'");    // '     Company X Product Z Professional     '

            companyProductStr = strHelper.trim(companyProductStr, emptyStr);
            trace("'" + companyProductStr + "'");    // 'Company X Product Z Professional'
        }
    }
}

class StringHelper {
    public function StringHelper() {
    }

    public function replace(str:String, oldSubStr:String, newSubStr:String):String {
        return str.split(oldSubStr).join(newSubStr);
    }

    public function trim(str:String, char:String):String {
        return trimBack(trimFront(str, char), char);
    }

    public function trimFront(str:String, char:String):String {
        char = stringToCharacter(char);
        if (str.charAt(0) == char) {
            str = trimFront(str.substring(1), char);
        }
        return str;
    }

    public function trimBack(str:String, char:String):String {
        char = stringToCharacter(char);
        if (str.charAt(str.length - 1) == char) {
            str = trimBack(str.substring(0, str.length - 1), char);
        }
        return str;
    }

    public function stringToCharacter(str:String):String {
        if (str.length == 1) {
            return str;
        }
        return str.slice(0, 1);
    }
}