Skip to content
Science, Maths & Technology
Author:

Strings and 'for' Loops

Updated Monday 29th June 2015

Learn how to do some more advanced tasks using strings and for loops.

A man sits on a sofa, checking a laptop computer Copyright free image Icon Copyright free: Startupstockphotos via Pixabay Previously you met the concept of a string as an object and the string method charAt() which returns the character at the specified position in the string (starting at index 0).

In addition to being associated with methods, which define their behaviour, objects are associated with properties, which hold information related to their structure and state (value). String objects have one such property called length which, as you might guess, holds the number of characters in the string. The existence of the length property, coupled with the fact that we can access characters at particular positions in the string using charAt(), means that for loops are ideally suited for processing the characters in a string. You will see some examples of this later in this section. First we explain how to use the length property.


Activity 1

The following code is from for_strings_activity_1.html. It repeatedly prompts the user to enter a string, and displays its length until the user enters a terminating string, end.

var myString; // string entered by user
// initialise myString to an empty string
myString = '';
while (myString != 'end')
{
myString = window.prompt('Please input a string; enter end to finish','');
document.write('The length of ' + myString + ' is ' +
myString.length + '<BR>');
}
document.write('Thank you');

Note that the 'dot' notation (myString.length) is used to indicate a property associated with an object.

Think of some strings of different lengths and kinds, including the empty string and some strings that contain spaces. Write down what you think the output of the program would be for each of these strings. Run the program to check your answers.

Answer

You should have found that in all cases the length property gave the exact number of characters in the string, regardless of the type of character. Here are some example strings and their lengths. For example:

String Length
'hello' 5
'' (empty string) 0
'******' 6
'hello world' 11
'123456789' 9
'length of myString' 8
'end' 3

Question:  What is the value of the number n for which myString.charAt(n) returns the first character of myString?

Answer

The value of n is 0. Remember that in JavaScript the indexing of characters in a string begins with index 0.

Write a line of JavaScript code which obtains the index of the last character in the string myString and assigns it to the variable lastIndex. (Hint You will need to use the length property of the string to find out how many characters it has.)

Solution

The line would be:

lastIndex = myString.length – 1;

Because the first character in the string is indexed 0, the last character is indexed to the value of the length minus 1. For example, a string of length 3 will have characters indexed 0, 1 and 2.


As mentioned earlier, we can use a for loop, the length property and the charAt() method to iterate through a string, character by character, as illustrated in the figure below. 

Process for using a string within a 'for' loop. First process statements before the for loop. Then initialise the counter to 0. Test: is the counter equal to the length of the string? If it is not, process the current character (accessed by using ChatAt()). Increment the counter by this value and test again. If it is now equal to the length of the string, carry on with statements after the for loop.

Activity 2

In this activity we want you to write a program which reads in a string from the user and outputs the characters, each followed by an asterisk. So, for example, if the user inputs the string hello, the output will be:

h*e*l*l*o*

You may still have the javascript_template.html file which we provided previously. If you don't, download it again. Open this file in the text editor and insert your code where we have indicated. Test your program by running it with a number of different strings.

Solution

Here is our code:

var myString;
myString = window.prompt('Please enter a string','');
//Remember -the arguments to charAt() start at 0, not 1
for (var count = 0; count < myString.length; count = count + 1)
{
    document.write(myString.charAt(count) + '*');
}

Did you remember to use the dot notation with both length and charAt()?

You will find a working solution in for_strings_solution_2.html.


Activity 3

Here is the code from for_strings_activity_3.html.

var word, letter;
word = window.prompt('Please enter a word','');
for (var count = 0; count < word.length; count = count + 1)
{
    letter = word.charAt(count);
    if (letter == 'e')
    {
        document.write('*');
    }
    else
    {

        document.write(letter);
    }
}

Note the use of the if statement inside the for loop. Note also our indentation to show the structure of the code.

(a) Think of a few words of different lengths and write down what you think the output of the program will be when each of these words is input. Run it using your words and check whether you are right.

(b) Open the program in your text editor and amend the program so that instead of doing what it did in part (a), it displays the number of occurrences of the letter e in the input word.

Solution

(a) The program reads in a word from the user, and displays it with any occurrences of the letter e replaced by asterisks.

(b) Here is our code.

var word, total;
word = window.prompt('please enter a word','');
total = 0;
for (var count = 0; count < word.length; count = count + 1)
{
    if (word.charAt(count) == 'e')
    {
        total = total + 1;
    }
}

document.write('The number of occurrences of e in the word '
                + word + ' is ' + total);

Note the way we have used word.CharAt(count) directly in the statement to avoid the need for the variable letter.

You will find a working solution in for_strings_solution_3.html.

(a) What factor would you consider when deciding whether to use a while loop or a for loop in a program?

(b) What are the three parts of the loop control statement in a for loop?

(c) What happens when the condition controlling a while loop evaluates to false?

(d) What must you always include in the body of a while loop?

Answer

(a) If you knew in advance how many repetitions would be needed, you would probably use a for loop, but if you did not know, you would need to use a while loop.
(b) The three parts are:

  • declaration and initialisation of a counter variable;
  • a condition specifying the finishing value of the counter;
  • a statement to increment or decrement the counter.

(c) The program jumps to the statement (if any) directly following the body of the while loop.
(d) A statement or statements which will eventually cause the controlling condition to evaluate to false.


Conditional statements (such as the if statement), while statements and for statements are all kinds of control structures, so called because they control the flow of execution of the program, i.e. the order in which statements are executed. This flow of execution, which is dependent on the evaluation of Boolean conditions, is often called the flow of control.

In this section, we have discussed the use of the for statement, which uses a counter to control the number of executions of a sequence of statements.

We revised the charAt() method of string objects and introduced you to the string property length.

Conclusion

If you have been through all of our Introduction to Programming Using JavaScript articles, you should now be much more familiar with how a variety of programming conventions work, as well as a greater familiarity with JavaScript in particular. Many programming conventions remain the same regardless of the language they are written in, the primary difference is in how they are presented. Re-visit any of the articles below or read more about JavaScript Style and Layout if necessary.

 

Author

Ratings

Share

Related content (tags)

Copyright information

For further information, take a look at our frequently asked questions which may give you the support you need.

Have a question?