<%response.buffer=true%> <% yere = year(date()) Response.Expires = 0 %> JavaScript Strings
<strings>
  spacerspacer

String Handling

Strings Defined: Strings are any series of "alphanumeric" characters treated as a separate entity. Strings can be thought of as 'nonsense' characters to JS, because a string implies that JS must keep the characters in proper sequence, and deliver them when asked, but NOT understand the significance of the contents involved. Frequently the contents of strings are HTML delivered to the page via document.write. JS knows very little about HTML. That would be our job!

String Handling: When we manipulate strings, we call that string 'handling'. With it we can identify browsers (browser sniff) and validate forms for completeness and accuracy. We can also use form handling to manipulate data, for example, to capitalize names, etc.

Eval Form: As an aid to understanding, you can test much of the code below in our Eval Form.

Strings in Variables: When we store strings inside a variable, we are storing the string inside a powerful object, from which we can manipulate the string:

var myString = "The Cat";

Strings variables are objects themselves in JavaScript. We can access certain methods (actions) and properties (qualities) of string objects by calling a variable that is the name of the string, with the dot syntax:

myString = "The Cat";
myString.toUpperCase();

This changes the case of each letter of the string to upper case, for example: THE CAT

Note the presence of the parens (), which makes toUpperCase() a method. If there were no parens, we would be working with the string object as a property. The length property (discussed below) is an example.

length & index: To be able to navigate around (and manipulate) a string, we need to be able to determine how many characters are in the string. We do this with the length property:

var myString = "Tyrannosaurus";
myString.length; //returns 13, the number of characters in the word

Note the number returned is the count of the number of characters in the string, starting with the number one.

However, we can also determine the index (position) of any character in the string, by using the indexOf() method:

var myString = "Tyrannosaurus";
var pos = myString.indexOf("T");
//returns 0 (zero) the integer "index" (position) of the first capital "T" in string

What's odd above is the first character of the 13 character string "Tyrannosaurus" returns zero, not one! This is because programs almost always count starting at zero! The characters in the string "Tyrannosaurus" are the numbers zero to 12. While the length of the string is 13.

length of Zero: The reason why we count starting at 'one' for the length is that it is possible to have a string with a length of zero:

var myString = "";
myString.length; //returns 0, the number of characters in an 'empty' string

We call the above a 'string of zero length' because it technically is a string, but we placed 'quotes' to indicate there is nothing currently visible. We'll do this to assign a neutral value to a string variable which makes it safe in case nothing else is ever placed in the variable. Using document.write will now not crash, because something is there (as far as JS is concerned) but nothing will show up on the page, thereby avoiding an error!

A Needle In A Haystack: There are times we wish to 'find' a string inside another string. The string we are trying to find is sometimes called the 'needle' and the string we looking through is the 'haystack'.

When we use indexOf(), we return an integer that represents the position of the first character of the needle, in the example below, the characters "he":

var myString = "The Cat";
myString.indexOf("he"); //returns 'one' indicating the string "he" begins at position one, the second char of the string

What happens if we search for a 'needle' that is not in the haystack? Lets search for the needle "Tyrannosaurus" inside the haystack "The Cat":

var myString = "The Cat";
myString.indexOf("Tyrannosaurus"); //returns -1 indicating there is no "Tyrannosaurus" in "The Cat"

The indexOf() above returns -1, which seems odd. Zero indicates the first character, so -1 is needed to indicate the needle is not found inside the haystack.

As a basis of comparison, view the following:

var myString = "The Cat";
myString.indexOf("t"); //returns 6 indicating the index of "t" as the last letter of "The Cat"

String Methods & Properties: Here are some of the main methods and properties of the string object, followed by a quick example of its use:

charAt() Determines which character resides at a particular index/position in a string:
var myString = "The Cat";
myString.charAt(0); //returns "T" which is the character at the first position in the string

indexOf() Returns the index/position of the first occurence of a string inside the string (returns -1 if not found):
var pos = myString.indexOf("http://"); //if myString includes "http://" the return would usually be zero since the characters are found in the very first position. (NOTE: If the characters are not found at all in the string, then -1 is returned.)

lastIndexOf() Returns the position of the last occurence of a string inside the string (returns -1 if not found):
var pos = myString.lastIndexOf("g"); //if myString is "eggs" the return would be 2 (third character).

NOTE: Both indexOf() and lastIndexOf() accept an optional second parameter as the starting point of the search. The correct syntax in that case would be: lastIndexOf("http://",22) to search starting at 23rd character. Remember this is zero based.

substring() Pulls out a partial string from the original string. Starts at the position of the first parameter, ends at the second parameter:
var myString = "The Cat";
myString.substring(4,6); //returns "Ca". If no second parameter, returns remainder.

It's frequently useful to extract everything starting at one point, without needing to indicate how far the end of the string is. Note the example above returns "Ca" not the entire word "Cat". We can use substring() with only one parameter, and return everything beyond the single provided parameter:

var myString = "The Cat";
myString.substring(4); //returns "Cat". No second parameter, so entire string beyond character at 4th position is returned.

slice() A more flexible version of substring(). Can accept negative values, otherwise works the same as substring:
var myString = "The Cat";
myString.slice(-3,-1); //returns "Ca", starting from end of string, working backward.

substr() An entirely different version of a 'sub' string. Pulls out a partial string from the original string. starts at first parameter, the second parameter is the length of characters returned:
var myString = "The Cat";
var newString = myString.substring(0,3); //returns "The".

toUpperCase() Changes entire string to upper case characters.
var newString = myString.toUpperCase(); //if myString is "The Cat", newString would be "THE CAT"

toLowerCase() Changes entire string to lower case characters.
var newString = myString.toUpperCase(); //if myString is "The Cat", newString would be "the cat"

NOTE: Both "toUpperCase()" and "toLowerCase()" change the ORIGINAL string, as well!

To demonstrate the capabilities of the various string handling functions, please see (and work with) the following form. Example: String Test Form

This form will allow you to type in strings, and see how the different string functions operate, and what they return.

Identifying The Current Page: We can use the href property of the location object to determine the current web address, as seen on the the address bar of the current browser window.

Imagine we have a page called "mypage.htm" on a site called "mysite.com".  Here is the string that is returned from the href property of the location object:

http://www.mysite.com/mypage.htm

We want to extract JUST the actual web page address, "mypage.htm" (without the domain, etc.).  To do this, we can find the position of the last "forward slash" using lastIndexOf():

var mySlash = location.href.lastIndexOf("/") //grab position of last forward slash

Next we can use the number returned to pull out the part of the string that immediately follows the last slash by using substring():

var thisPage = location.href.substring(mySlash + 1); //returns "mypage.htm"

We needed the +1 above because we didn't want to include the slash. The variable thisPage now includes the current file name, with the subdirectories and domain named stripped from it. We can use this to determine which page we are on, and vary the data on the page, based upon the current address.

Stacking: We can 'stack' functions and methods, one inside the other. This can make things look much messier, but JS is not confused, as long as we remember the order of operations. JS will go to the inner-most parens, and do what is requested there, and work it's way to the outside. Note the following JS does what we did above, in one single line of code:

location.href.substring(location.href.lastIndexOf("/") + 1);

Check it out in the Eval Form!

   
Print this Page Back To Top

2000- <%=yere%> newMANIC INC, All rights reserved