Did it never occur to you, working with text strings, the need to extract only a part of that string?
In this article, I will show you how to use the substr() and substring() methods of the String Class in
Actionscript 3.0.
Both of them returns a string value based on the 2 parameters received.
Let's take a look at them...
The substr() method.
wants two pararmeters:
- startIndex: an integer that indicates the position of the first character to be used
- length: the number of characters extracted after the startIndex
The substring() method.
wants two parameters:
- startIndex: an integer that indicates the position of the first character to be used
- endIndex: an integer that indicates the position of the last character to be used
To better understand these 2 methods, I created a Document Class as example:
Code:
package
{
import flash.display.MovieClip;
public class Substringa extends MovieClip
{
public function Substringa()
{
init();
}
private function init():void
{
var testo:String='FlepStudio';
trace(testo.substr(0,4));
trace(testo.substring(0,4));
trace('-------------------------');
trace(testo.substr(1,5));
trace(testo.substring(1,5));
trace('-------------------------');
trace(testo.substr(4,6));
trace(testo.substring(4,6));
trace('-------------------------');
}
}
}
The output returned by Flash is the following:
Quote:
Flep
Flep
-------------------------
lepSt
lepS
-------------------------
Studio
St
-------------------------
|
Let's analyse the code.
I have a String variable with some text
var testo1:String='FlepStudio';
First case:
I use substr() passing the values: zero as startIndex (so it will start from the first character) and 4 as length (it will move of 4 positions starting from the first character)
trace(testo1.substr(0,4));
I use substring() passing the values: zero as startIndex (so it will start from the first character) and 4 as endIndex (it will move till the fourth position and stop)
trace(testo1.substring(0,4));
Second case:
I use substr() passing the values: 1 as startIndex (so it will start from the second character) and 5 as length (it will move of 5 positions starting from the second character)
trace(testo2.substr(1,5));
I use substring() passing the values: 1 as startIndex (so it will start from the second character) and 5 as endIndex (it will move till the fifth position and stop)
trace(testo2.substring(1,5));
Third case:
I use substr() passing the values: 4 as startIndex (so it will start from the fifth character) and 6 as length (it will move of 6 positions starting from the fifth character)
trace(testo.substr(4,6));
I use substring() passing the values: 4 as startIndex (so it will start from the fifth character) and 6 as endIndex (it will move till the sixth position and stop)
trace(testo.substring(4,6));
Stay tuned !