Previous Topic Tutorial Table of Contents Next Topic
JavaScript tutorial
 
 

The String Object

Strings are "strings of characters".  A word is a string, a set of words is a string, a set of words, numbers and punctuation marks can be a string.  So what is a string object?

A string object is a place of storage for any string you want to create.  There are two ways to create a string object:

var s1 = "My name is Johnny";
var s2 = new String("My name is Mary");

You can also use an "anonymous string" (meaning that a variable name has not been assigned to it) inside methods that require strings as an argument. For example, when using the document.write() method you can give the string argument as a string variable:

document.write( s1 );

or as an anonymous string:

>document.write( "My name is Johnny" );

You can add onto a string by using the "+" operator.  For example:

var s3 = "Then she said: " + s2 + ". What is yours?";

s3 now equals:
Then she said: My name is Mary. What is yours?<

How do we add in quotation marks so that s3 looks like this:
Then she said: "My name is Mary. What is yours?"

Normally, the quotation mark in a string acts as an operator, delimiting the beginning or end of the string.  To add quotation marks to the string itself, you have to use the backslash operator "\", which can be read to mean: take the next character literally, not as an operator.  So one would change the code to read:

var s3 = "Then she said: \"" + s2 + ". What is yours?\"";


The real of power of having string objects is that they come with a large number of powerful methods.  I will demonstrate the use of five important string methods here:

toUpperCase()
toLowerCase()
charAt()
substring()
split()

and one important property of strings: length (String objects do not have any event handlers because they are not part of the DOM hierarchy.)


toUpperCase() and toLowerCase()

These functions can be used to transform your string and return a new string which is all uppercase or lowercase.

var s1 = "Good day";>
var s2 = s1.toUpperCase();

s2 now equals "GOOD DAY

These functions can be useful for comparing two strings (such as user input in a form and strings preset in your script) when you don't care about capitalization.<


charAt()
The charAt() method takes an integer argument that specifies the position of a character in a string and then returns that character.  Note that the first character position in a string is zero, not one (this is called zero-based indexing).  Here's a demonstration:

var s1 = "Fred Flintstone";
var c1 = s1.charAt(2);
var c2 = s1.charAt(4);

c1 now equals the letter 'e' and c2 now equals the character 
'' (a single space).

One use of charAt() is in grabbing the first character of the appVersion property of the navigator object when trying to determine what level of browser a user has.  For instance:

if (parseInt(navigator.appVersion.charAt(0))> 3) 
{
    //do something specific to level 4 or 5 browsers
}

The global function parseInt() has to be used here because charAt() returns a character.  parseInt() transforms that character into a number and then a numerical comparison is made.


substring()
The substring() method is similar to charAt() in that it grabs a part of a larger string and returns that value. It returns a string, however, not a character. (It can return a single character "string", but you should use charAt() for this.)

substring() takes two integer arguments.  The first integer is the index position of the first character to grab.  The second argument is the index value of one character after the last one to be grabbed.  One way that helps me to remember this is to count how many characters you want to extract and add it to the starting index value:  that value will be your second index value.

var txt = "Power to the people!";
var subtxt = txt.substring(0,3);
var subs = txt.substring(6,14); 

subtxt now equals "Pow".
subs equals "to the p"


split()M
Every programming language needs a way to cut up long strings into tokens or elements.  JavaScript is no exception.  The string split() command takes a character or regular expression as its argument and splits the string into tokens based upon the delimiter character.

[SIDE NOTE]
A regular expression is a highly idiomatic format for describing pattern matching and will not be discussed in this tutorial. However, if you are interested in doing string processing, regular expressions are an extremely useful and powerful tool. One example script I've written shows how they can simplify your text processing programs.

As split() returns a series of strings, the variable you define to capture them will be an array. Here's an example:

var list = "George,John,Thomas,John Quincy";
var presidents = list.split(",");
var nonsense = list.split("");

presidents is now an array with four elements:
George
John
Thomas
John Quincy

while nonsense is an array with two elements:
George,John,Thomas,John
Quincy

Note that the string list is unchanged by the action of the split()

You can also specify a delimiter string, instead of a single delimiter character.

If the list above had spaces after each of the commas, like so: "George, John, Thomas, John Quincy", then you should specify ", " (a comma followed by a space) as the delimiter string.

To demonstrate, this link opens up a window that demonstrates the values of each string and array from the following bit of code:

var list = "George,John,Thomas,John Quincy";
var list2 = "George, John, Thomas, John Quincy";
var presidents = list.split(",");
var nonsense = list.split(" ");<
var a = list2.split(", ");



The String length Property

The length property of string can be useful in a number of ways.  It can be used to set an index value in charAt() or substring() that is relative to the end of the string. For example, suppose you wanted to grab the second to last character of some string. Instead of counting what the index value of that character would be, you could write:

var c = string1.charAt( string1.length- 2 );

You have to use length - 2 here because the last character of a string is at index length - 1, due to zero-based indexing.

Another use of length is in for loops when you want to interate over every character in a string. For example:

for (var i = 0; i < string1.length; i++) {

    if (string1.charAt(i) == 'e') {
       //do something with the match
    }
}

Again, because the value returned by string1.length is one greater than the index position of the last character in string1, you write:

i < string1.length

in the for loop, not:

i <= string1.length

The latter statement would incorrectly go one position beyond the last character in string1.

See this example script for a demonstration of the use of some of these methods and properties.


Previous Topic Tutorial Table of Contents Next Topic