Skip to content
Science, Maths & Technology

More About Strings

Updated Monday, 29th June 2015

Learn how to work more in-depth with strings in JavaScript.

This page was published over five years ago. Please be aware that due to the passage of time, the information provided on this page may be out of date or otherwise inaccurate, and any views or opinions expressed may no longer be relevant. Some technical elements such as audio-visual and interactive media may no longer work. For more detail, see our Archive and Deletion Policy


A man sits on a sofa, checking a laptop computer Copyright free  image Icon Copyright free: Startupstockphotos via Pixabay In Introducing the while Statement and The while Sentinel, you have seen the repeated processing, using a while loop, of a succession of strings and of a succession of numbers. We now consider the repeated processing of a succession of characters within a string.

First, you need to find out a bit more about strings. In JavaScript, strings are object types and, as with other JavaScript objects such as Document and Window, which you have already encountered, they have a number of methods associated with them. We start by discussing one such method, charAt().

Activity 1

The aim of this activity is to introduce you to the method charAt() associated with string objects.

The following code is from strings_activity_1.html.

var myString;
myString = window.prompt('Please enter a string with exactly 5 characters','');
document.write('You have chosen the following word ' + myString + '<BR>');
document.write('The character in the first position is ' + myString.charAt(0) + '<BR>');
document.write('The character in the fifth position is ' + myString.charAt(4) + '<BR>');

(a) Think of a string with exactly five characters. Can you guess what the output from the program would be if you entered this string? Run the program and find out whether you were right.
(b) What do you think myString.charAt(n) does, where n is some number?


(a) The output will be the specified output strings in the last two lines of the code, together with the first and last characters from the input string. For example, if the word input had been hello, the output would have been:

You have chosen the following word hello
The character in the first position is h
The character in the fifth position is o

(b) You might have guessed from our use of the numbers 0 and 4 to output the first and fifth characters in the string that myString.charAt(n) will return the character in the position after n in the string myString. The characters in a JavaScript string are numbered (we say indexed) from 0 to one less than the number of characters. So myString.charAt(0) returns the character that is the first in the string assigned to the variable myString (starting from the left); myString.charAt(4) returns the character in the fifth position from the left.

Write a JavaScript statement, similar to the ones above, which will output the third character from the left in a string assigned to the variable myString.


You would need to write the following line of code:

document.write('The character in the third position is ' + myString.charAt(2)+ '<BR>');

Open strings_activity_1.html in your text editor and add the following line at the end of the JavaScript code.

document.write('The character in the last position is ' + myString.charAt(5)+ '<BR>');

Run the program, inputting a string of five characters as before. What happens, and why?


The last line of output will be:

The character in the last position is

This is because myString.charAt(5) returns the character in the sixth position – and you have only entered five characters. What number would you need to use to make this line work as intended?

Activity 2

In this activity you are going to write a program which searches a word for a particular letter, in this case e, and writes out its position in the string. So, for example, if you input the word 'tea', the following would be displayed.

The first occurrence of letter e is in position 2 in the word tea

You may assume that there is at least one occurrence of e in the string. Download our JavaScript Template if you need a fresh copy. Open the file with the text editor and include your JavaScript code, then test it with some words which contain e.

If you test your code with a word that does not contain an e, the program will go into an infinite loop, as described in Exercise 4.1. If this happens you will need to use the Windows task manager, or Force Quit on Mac, to stop your browser running.

Thinking about the program

Before you start writing your code, it might help to ask yourself the following questions.

(a) You need to go from letter to letter, testing each one. Which JavaScript construct allows you to repeat processing for a number of different values?
(b) Which method allows you to consider individual letters in a string?
(c) How many variables will you need?
(d) How will you initialise the variable(s)?
(e) How are you going to test whether a letter at a particular location, indexed by a variable called, say, index, is not the letter e?
(f) If the letter in a particular location is not the letter e, what should happen to the value of index?
(g) If a letter in a particular location is the letter e, what do you need to display?

Having answered these questions, write the program.


(a) The construct you need is a while loop.
(b) charAt() returns the character in the location specified by the number in the argument , i.e. the number enclosed within parentheses. Remember that the numbering starts with 0, rather than 1.
(c) You need a variable to hold the string, called for example myWord, and also a variable called index to hold the current value of the location.
(d) The value of myWord is initialised using window.prompt(); index is initialised to be in the first position, which is indexed 0 (not 1!).
(e) The test is (myWord.charAt(index) != 'e').
(f) If the test succeeds, i.e. a letter in the current location is not e, you want to consider the letter in the next location and advance index by 1, using index = index + 1.
(g) Because JavaScript considers the position of a character in a string to be one less than the usual convention for humans, we need to add 1 to index to give a more meaningful position in the output.


Here is our code.

var myWord, index;
myWord = window.prompt('Please enter a word which has an e in it','');
index = 0;
/* The loop goes from letter to letter stopping when it reaches */
/* the letter e                                                 */
while (myWord.charAt(index) != 'e')
/* Once an e has been located, the program skips to the         */
/* instruction following the body of the loop, which adds one   */
/* to index to compensate for the fact that the first character */
/* is at position 0 rather than 1                               */
document.write('The first occurrence of letter e is in position '
                 + (index + 1) + ' in ' + myWord);

You can download our solution - strings_solution_2.html - if you need it.

Activity 3

Now extend the program so that it works with any letter, not just the letter e. The program should prompt the user to enter first their chosen letter, then a word with that letter in it. The position of the first occurrence of that letter in the given word is then displayed.

You may want to use our solution to the previous activity as your starting point.


Here is our code.

var letter, myWord, index;
letter = window.prompt('Please enter your chosen letter','');
myWord = window.prompt('Please enter a word which has a(n) ' + letter + ' in it','');
index = 0;
while (myWord.charAt(index) != letter)
document.write('The first occurrence of letter ' + letter
                 + ' is in position ' + (index + 1) + ' in ' + myWord);

You can download our solution - strings_solution_3.html - if necessary.

In this section, we discussed the while statement, often called a while loop, which enables you to repeat the execution of a sequence of statements, constituting the body of the loop, until some Boolean expression at the start of the loop evaluates to false. You saw how while loops can be used to guard against incorrect input by prompting the user to re-enter input until it is in the correct form, and also how they can be used to repeat execution until some stopping value (sentinel) is reached.

We introduced the idea of a string as an object consisting of a number of characters, and you met the method charAt(), which returns the character at a particular location in the string determined by the argument to the method. We noted that the positions of characters in a string are numbered (indexed) from left to right, with the leftmost character having the index 0.

If you want to learn more about programming for repetition, move onto the next article, Introducing the for Loop.




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?