Tutorials Books Videos Forums

-- online Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Using Strings

by kirupa   | filed under Flash and ActionScript

This is an archived tutorial from the kirupa.com legacy collection. It covers software that may no longer be available, but it is kept online because the ideas still hold up.

Have you ever thought about the text that you are reading on your computer? More than likely not, and that's good. There are far better things to do with one's time. But, as a programmer, you will find yourself having to display textual information to the screen. You might be expected to generate text based on what your program is doing, and that is often more complicated than simply displaying pre-formatted text. Essentially, you now have to figure out how text is used in Flash and what things you can do to manipulate your text.

Everything you display on your screen is nothing more than a series of small characters. Usually, these characters are letters or numbers. A collection of such small characters is called a string.

In Flash, you have the String class that takes care of many of the grungy details associated with making something a string. If you are not familiar with OOP concepts such as class/methods/objects, you may want to give senocular's OOP Tutorial a whirl first!

You can declare variables as String objects by following your variable name with the String type:

var stringData:String = "Hello!";

Because stringData is a variable of type String, it has access to all of the built-in methods (features) of the String class. Many common functions that you would want to use with strings have already been developed for you by the Flash developers. The full list of String methods you can use can be found by clicking here [external link].

In this tutorial, I will explain how to use the String class and many of its methods to create a dollar amount parser. By the end of this tutorial, you will have learned how to think about strings as a series of characters, and how to manipulate them using the String class's methods.

Getting back to our tutorial's goal, the dollar amount parser is a function that takes in a number and returns a dollar amount complete with the dollar sign ($), commas (,), and the right number of digits after the decimal point (.).

Let's build our dollar amount parser incrementally. That allows you to get a feel for how to use strings if you are just starting out with ActionScript, and it helps me to explain more complicated concepts by making references to earlier, easier topics.

Just for reference, you will find our full code below. Don't worry about the code now, though, for you will incrementally be introduced to the code in the tutorial:

dollarParser = function () {
  var input:Number = 1567.5644;
  var inputString:String = input.toString();
  var decimalIndex = inputString.indexOf('.');
  var centString:String = inputString.substring(decimalIndex, decimalIndex+3);
  var dollarString:String = inputString.substring(0, decimalIndex);
  //
  var finalString:String = "$";
  var count:Number = 0;
  var tempString:String = "";
  for (var i:Number = dollarString.length-1; i>=0; i--) {
  count++;
  tempString += dollarString.charAt(i);
  if ((count%3 == 0) && (i - 1 >= 0)) {
  tempString += ",";
  }
  }
  for (var k:Number = tempString.length; k>=0; k--) {
  finalString += tempString.charAt(k);
  }
  finalString += centString;
  trace(finalString);
};
dollarParser();

The above code might not make much sense, but in the next few pages, you will realize that all of this isn't so complicated after all!

In the previous section, I introduced strings and how all string objects are extensions of the String class in Flash. In this page, we will start deconstructing the previous code in order to create our dollar parser.

Let's get started!

Create a new animation in Flash. This tutorial will be all code-based, so right click on the empty keyframe in your timeline and select "Actions". Your actions window should appear:

Let's first create the function to house all of our code. Copy and paste the following code into your Actions Window.

dollarParser = function () {
  trace("Hello!");
};
dollarParser();

In the above lines of code, I create a new function called dollarParser and add a trace action inside. I immediately make a call to our dollarParser function. If you test this animation by pressing Ctrl + Enter, you will see the "Hello" text display in our Output window:

Because it is difficult to visualize code output if you are just starting out with programming, I will be using trace actions frequently at the beginning. In this case, I added a trace text simply to show you that our dollarParser() call (line 4) calls our dollarParser function.

Let's declare some variables! Replace our above dollarParser function with the following code:

dollarParser = function () {
  var input:Number = 1234567.5644;
  var inputString:String = input.toString();
}

I declare two variables - input and inputString. In order to work with strings, all of our variables need to be in the String format. From the above lines of code, our input variable is a Number object. We need to convert input into a String. That is where the second variable inputString comes in. I use the toString() method on our input variable to convert our Number data into a string.

With our input now stored as a String in the inputString variable, let's continue. First, let's work on getting our function to deal with the decimals properly. For this tutorial, for any input, there should be only two numbers after our decimal point. In other words, 45.23 is acceptable whereas 68.334 is not acceptable.

In the context of our code right now, to recap, we want our number 1234567.5644 to be 1234567.56. The extra 44 after the decimal point is not necessary. We accomplish that with three extra lines of code added to our dollarParser function:

dollarParser = function () {
  var input:Number = 1234567.5644;
  var inputString:String = input.toString();
  var decimalIndex:Number = inputString.indexOf('.');
  var centString:String = inputString.substring(decimalIndex, decimalIndex+3);
  var dollarString:String = inputString.substring(0, decimalIndex);
  trace(dollarString);
}

Be sure to add the three colored lines of code in the right location in your Actions panel. Test your movie in Flash. Notice that your Output Window displays the expected data from our input variable: 123456.

In the next section, I will explain what each line of your newly pasted code does!

In the previous section, you separated our input by differentiating between the whole dollar and the cents based on the position of the decimal point. I have not explained how the separation actually works. I will do that and more on this page!

Let's now take a look at what each new line of code you pasted from the previous section does.

var decimalIndex:Number = inputString.indexOf('.');

The indexOf method takes in a particular character as its argument and returns the numerical position of where it is located in our string.

The indexOf method always returns a number. It returns the index position of the first occurrence of the character inputted or a -1 if the string does not contain the character at all. In the above line of code, the string in question is inputString, and our indexOf method checks to see where the decimal point, the . character, occurs in our string.

You can think of a string as a collection of individual characters each at a particular, numerical position:

The first and only occurrence of the decimal point occurs at index position 7. If you trace the decimalIndex variable, you will see the number 7 displayed as the output from the indexOf method.

Let's look at the next line of code:

var centString:String = inputString.substring(decimalIndex, decimalIndex+3);

In this line of code, we store the two characters after our decimal point into our centString variable. I am able to do this easily by using the subString method. The subString method takes the starting index position and the ending index position plus one of our string and returns the characters in between the starting and ending positions.

In the code above, the range of characters lies between decimalIndex and decimalIndex + 3. One way of looking at it would be to think of the subString function boxing in the characters it wants. That would also explain why have to increment your final character's index position by 1:

So, the data stored inside centString based on the subString operation will be .44.

var dollarString:String = inputString.substring(0, decimalIndex);

We now have our cent information parsed out of our string. The above line of code takes care of everything else. The dollarString variable stores all the characters between inputString's starting position, index position 0, and the ending position up to the decimal point, decimalIndex:

Phew. That was a lot of explanation for what looks like a simple task! Luckily, the next three lines are simple variable declarations:

var finalString:String = "$";
var count:Number = 0;
var tempString:String = "";

We are declaring three variables: two String objects and one Number object. Let's focus on the two String objects. If you look through the code, you will see that I declare a lot of String objects. It almost seems like an unnecessary amount. The reason I do that is, in Flash and several other OOP languages such as C# and Java, String objects are unchangeable aka immutable. Once I initialize a String object, I cannot change it by adding more characters to it. I have to work around that by declaring new String objects that contain the original string and an operator that performs any string manipulation that I wish to accomplish.

For example, I cannot do the following:

var firstName:String = "kirupa";
firstName + " says hello!";
trace(firstName);

My output would still be kirupa instead of "kirupa says hello." I can, instead do two things to accomplish the same goal:

// Thing 1
var phrase:String = firstName + " says hello!";
trace(phrase)
// Thing 2
firstName += " says hello!";

Both of the above approaches, which I cheekily call Thing 1 and 2, end up tracing "kirupa says hello!" You might be wondering why Thing 2 works, but remember the += operator is the short-hand version of writing firstName = firstName + " saysHello". Technically, I am simply overwriting the old variables contents with a copy of the old variable data along with the new data.

Ok, I think I have sidetracked a little too much. Anyway, hopefully you have an understanding of why I am being a bit redundant by using many variable names in my code. In the next section, I will explain the rest of the code and wrap up the tutorial!

In the previous section, I finished explaining the part where the data was divided into separate variables. I also provided a brief explanation as to why we use so many variable names when dealing with strings in the first place.

Now, we are ready to add the commas to separate our digits. For example, a number such as 65536 should look like 65,536. The trick lies in knowing just when to start adding a comma. There are several ways to tackle this problem. The easy way is to add commas by traversing your string in a right-to-left direction.

Add the following colored code to do just that:

dollarParser = function () {
  var input:Number = 1567.5644;
  var inputString:String = input.toString();
  var decimalIndex = inputString.indexOf('.');
  var centString:String = inputString.substring(decimalIndex, decimalIndex+3);
  trace(centString);
  var dollarString:String = inputString.substring(0, decimalIndex);
  //
  var finalString:String = "$";
  var count:Number = 0;
  var tempString:String = "";
  for (var i:Number = dollarString.length-1; i>=0; i--) {
  count++;
  tempString += dollarString.charAt(i);
  if ((count%3 == 0) && (i - 1 >= 0)) {
  tempString += ",";
  }
  }
};
dollarParser();

In the above code, in the for loop, I move backwards through our string:

for (var i:Number = dollarString.length-1; i>=0; i--) {

I start at the end of our input by setting the count variable i to equal the last character of our string (dollarString.length-1) and I keep looping until our counter, i, becomes less than 0. I approaching zero is the same as you reaching the leftmost, first character in our word list.

We want to add a comma after three characters. The easiest way of doing so is to have a counter that increments and does something when its value becomes a multiple of 3. You can do that using the % (modulo) operator:

if ((count%3 == 0) && (i - 1 >= 0)) {
  tempString += ",";
}

Every time the count variable stores a number that is a multiple of three, our tempString character gets a , comma added. Our tempString variable, at the end of the loop, contains the properly formatted dollars.

My if statement actually contains two conditions. The first condition checks for multiples of threes. The second condition checks to see if there is a number after your current position. This ensures that, given a number such as 125, you do not end up with a comma preceding it, for example - ,125.

Now, all we need to do is take our tempString data and insert it into our finalString variable that currently only contains the $ sign. Add the following colored lines of code to your existing code:

dollarParser = function () {
  var input:Number = 1567.5644;
  var inputString:String = input.toString();
  var decimalIndex = inputString.indexOf('.');
  var centString:String = inputString.substring(decimalIndex, decimalIndex+3);
  trace(centString);
  var dollarString:String = inputString.substring(0, decimalIndex);
  //
  var finalString:String = "$";
  var count:Number = 0;
  var tempString:String = "";
  for (var i:Number = dollarString.length-1; i>=0; i--) {
  count++;
  tempString += dollarString.charAt(i);
  if ((count%3 == 0) && (i - 1 >= 0)) {
  tempString += ",";
  }
  }
  for (var k:Number = tempString.length; k>=0; k--) {
  finalString += tempString.charAt(k);
  }
};
dollarParser();

The above code cycles through our tempString, takes each character from it by using the charAt method, and adds it to the end of our finalString variable.

Note

Doesn't it seem inefficient to have two for loops that essentially cycle through the characters in a string? Yes, it is! The reason I use two for loops is because it is difficult to gauge the length of our tempString string prior to the commas being added. Therefore, adding values to our finalString after tempString has been properly populated with numbers and commas makes sense.

A better method would be to create an insert function that inserts the commas into the appropriate location on the string, but that is well beyond the scope of this tutorial.

There are more efficient ways, of course, but this tutorial is primarily focused on Strings. I don't want to introduce any more confusing conventions - at least not intentionally =)


At this point, tracing finalString will result in $1,234,567 being displayed. That's not bad, but we need to incorporate the cents information we dealt with earlier! The final two lines of code do that and finish up our re-creation of code I presented at the beginning of this tutorial:

dollarParser = function () {
  var input:Number = 1567.5644;
  var inputString:String = input.toString();
  var decimalIndex = inputString.indexOf('.');
  var centString:String = inputString.substring(decimalIndex, decimalIndex+3);
  trace(centString);
  var dollarString:String = inputString.substring(0, decimalIndex);
  //
  var finalString:String = "$";
  var count:Number = 0;
  var tempString:String = "";
  for (var i:Number = dollarString.length-1; i>=0; i--) {
  count++;
  tempString += dollarString.charAt(i);
  if ((count%3 == 0) && (i - 1 >= 0)) {
  tempString += ",";
  }
  }
  for (var k:Number = tempString.length; k>=0; k--) {
  finalString += tempString.charAt(k);
  }
  finalString += centString;
  trace(finalString);
};
dollarParser();

The following line sticks the data from our centString variable to the end of our finalString variable:

    finalString += centString;

When our output for finalString complete, the trace command will output the following number:

$1,234,567.56

And with that, you now have a rudimentary decimal number parser. It is not fully feature complete, and there are situations where you can break the program easily. Try entering in non-numerical data such as letters and see what happens, for example :-P

But, for the sake of understanding how to use strings and the String class's methods in Flash, I hope this tutorial helped.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--