JavaScript Strings


Character Sequences

At the most basic level JavaScript strings are sequences of text characters. The text characters may be symbols such as +/-%$#@, numbers such as 1234567890, and characters such as aàáâãäåæbcçdeè and so on. However, unlike lower level languages like C, the text characters cannot be directly manipulated within the string. Short one character strings can be extracted from a string and new strings can be built from smaller one character strings, but characters are not a separate datatype as in C.

Strings are often created in JavaScript by assigning literal text to a variable. For example:

welcome = "Hello World"

In this example we want the sequence of characters that spell out the words:

Hello World

to be stored in the variable welcome. To indicate that these characters are to be taken literally as text and not be interpreted as JavaScript variables or key words the characters must be enclosed in single or double quotes. Either can be used.

welcome = 'Hello World'

does the same thing as:

welcome = "Hello World"

String Objects

After the assignment of the literal string "Hello World", the variable welcome may be treated as a string object. Just as the document object had properties that could be read (and set) and methods that provide more complex functionality, JavaScript strings have properties that can be read and methods to perform useful functions. Here are some introductory examples showing some simple JavaScript statements where a value is returned to a variable named result. They do not completely document these methods.

Determining String Length

welcome = "Hello World"
result = welcome.length

The length property contains the number of characters that are in a string. In this example result will be assigned the number 11.

To make string length and the position of characters within the string easier to visualize the simple illustration below shows the eleven characters in the string Hello World numbered from 0 through 10. Note that because JavaScript strings start with the first character in position 0 the last character is always one less than the string length.

Getting a Single Character String

The charAt() method returns a single character string from a string object. It is passed the position in the string of the single character to return. The character returned is a copy of the character at that position within the string. The original string stored in this case in the welcome variable is unaffected.

result = welcome.charAt(0)

result is the character H

Getting a Portion (substring) of the String

Part of a string from one position to another can be returned using the substring() method. The first value to be passed to substring is the starting position of the string to return - in this example the first character in position 0. The second value (after the comma) is the character AFTER the substring that is NOT to be returned. In this case the space character in position 5 will be the first character to not be returned. Again, as with all these methods, a new string is being returned that is a copy or modified version of the original. The original string object is unaffected by these methods.

result = welcome.substring(0,5)

result is the string Hello

Searching for a String inside a String

It is often useful to be able to check for the location within a string of some smaller string. In this example the indexOf() method of the string object is used to look for the word World inside the welcome string. The position of the first character in World - the W - is returned if the string is found.

result = welcome.indexOf("World")

return is the number 6. If the string is not found indexOf returns -1.

Another method of the string object lastIndexOf() does the same thing but begins its search from the end of the string and finds the last occurence (if there is one) of the search value. In the following example lastIndexOf is used to find the last period in the string.

fileName = "my.picture.jpeg"
result = fileName.lastIndexOf(".")

In this case result is the number 10.

Changing Case

When user input is stored in a string it is often useful to convert it to all upper case or all lower case characters before checking what the user has entered. There are two methods that do this:

result = welcome.toUpperCase()

The toUpperCase function returns a copy of the string in the string object but with each letter capitalized. Result is HELLO WORLD

result = welcome.toLowerCase()

result is hello world

Here is a short script that writes out some of these values:

<HTML>
<HEAD><TITLE>Examples of using the JavaScript String Object</TITLE>
</HEAD>
<BODY>
    <SCRIPT Language="JavaScript">
    <!--
    var welcome = "Hello World"
    document.writeln("<PRE>")
    document.writeln(welcome)
    document.writeln(welcome.toUpperCase())
    document.writeln(welcome.toLowerCase())
    document.writeln(welcome.charAt(0))
    document.writeln(welcome.substring(0,5))
    document.writeln(welcome.indexOf("World",0))
    document.writeln("</PRE>")
    // -->
    </SCRIPT>

</BODY>
</HTML>

Using string methods together

The string methods - and there are more of them than listed here - are often used together to perform useful functions. For example: a user fills in a form including a file upload field that you are expecting contains a path to a JPEG formated file and you want to make sure the file has the extension .jpg, .jpeg, .JPG, or .JPEG. Assmuming the full path to the file has already been stored in a variable named path you might check the path by extracting the file extension and comparing it to the valid extensions. This short demonstration script writes a report into the document if the extension is correct or not. It also reduces the number of comparisons by forcing the extension extracted from the path to lower case. Finally, the script uses if else statements to make decisions - these are described later.

<HTML>
<HEAD>
<TITLE>Using lastIndexOf, length, substring, and toLowerCase together</TITLE>
</HEAD>
<BODY>
<PRE>
<SCRIPT>
<!--
// This short script demonstrates how a number of string methods
// can be used together to check the extension of a file name.

path = "C:\pictures\mmProject11\assembly3.jpg"   //sample file name for testing - change this and rerun the script

errorMsg = "Invalid File Name. File must have a .jpg or .jpeg extension." //standard error message

start = path.lastIndexOf(".")                    //find the last period character in the string
if (start == -1){                                //if there isn't one report the problem
   document.writeln(errorMsg)
}
else{
   start++                                       //the first character of the extension is the one after the .
   
   extension = path.substring(start, path.length).toLowerCase()  //force the rest of the string to lower case
   
   if ((extension == "jpg") || (extension == "jpeg")){   //if extension is jpg or jpeg then it's ok.
      document.writeln("The extension is correct.")
   }
   else{                                                 //otherwise report the error
      document.writeln(errorMsg)
   }
}   
//-->
</SCRIPT>
</PRE>
</BODY>