Learn Javascript
String Processing
Join the Discussion
More of this Tutorial
Reference
Introduction
The string class is another built in class that is slightly different from the normal. Where this class differs from all of the others is the way that you define objects of this type. You have in fact already learned how to do this in the very early tutorials in this series. Any variable that you define as having a text value is automatically a string object and all of the string methods can be applied to it. It is not necesssary to define the object as new String.
String Methods
There are quite a few methods provided by the string class that allow you to manipulate text strings. Some of these methods that you will probably find many uses for include the following:
- charAt(number) selects the single character at the specified position within the string
- indexOf(substring) finds the position where the specified substring starts
- lastIndexOf(substring) finds the last occurrence of the substring within the string
- substring(start,end) or substr(start,length) gets the specified part of the string
- toLowerCase() convert the string to lowercase
- toUpperCase() convert the string to uppercase
- split(char) splits the string at each occurrence of the specified character and puts them into an array
You will probably find yourself using these string methods far more than most of the other parts of the Javascript language particularly if you are writing Javascript to validate forms.
Using String Methods
Even though you don't define string objects the way that you do objects belonging to other classes, the way that you access the methods is exactly the same as for other classes in that you specify the name of the object followed by a period and then the name of the method. Let's look at an example:
document.write(txt.substr(5,6));
This code will print the word sample without the surrounding text (or spaces).
Using What You Know
Suppose that we have a text field containing a number of entries separated by commas that we require to have processed as separate entries. We can easily convert our comma separated list into an array of entries in one simple command like this:
var arry = txt.split(',');
Now arry[0] contains 'a', arry[1] contains 'b', and so on making it easy to then process the entries in the array using a for or while loop.

