|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Working with SubstringsSo far, you've worked with entire strings. JavaScript also enables you to work with substrings, or portions of a string. You can use the substring method to retrieve a portion of a string, or the charAt method to get a single character. These are explained in the following sections. Using Part of a StringThe substring method returns a string consisting of a portion of the original string between two index values, which you must specify in parentheses. For example, the following statement displays the fourth through sixth characters of the text string: document.write(text.substring(3,6)); At this point, you're probably wondering where the 3 and the 6 come from. There are three things you need to understand about the index parameters:
As another example, suppose you defined a string called alpha to hold the alphabet: alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; The following are examples of the substring() method using this string:
Getting a Single CharacterThe charAt method is a simple way to grab a single character from a string. You specify the character's index, or position, in parentheses. The indexes begin at 0 for the first character. Here are a few examples using the alpha string:
Finding a SubstringAnother use for substrings is to find a string within another string. One way to do this is with the indexOf method. To use this method, add indexOf to the string you want to search, and specify the string to search for in the parentheses. This example searches for "this" in the test string: loc = test.indexOf("this");
By the Way As with most JavaScript methods and property names, indexOf is case sensitive. Make sure you type it exactly as shown here when you use it in scripts. The value returned in the loc variable is an index into the string, similar to the first index in the substring method. The first character of the string is index 0. You can specify an optional second parameter to indicate the index value to begin the search. For example, this statement searches for the word fish in the temp string, starting with the 20th character: location = temp.indexOf("fish",19);
By the Way One use for the second parameter is to search for multiple occurrences of a string. After finding the first occurrence, you search starting with that location for the second one, and so on. A second method, lastIndexOf(), works the same way, but finds the last occurrence of the string. It searches the string backwards, starting with the last character. For example, this statement finds the last occurrence of Fred in the names string: location = names.lastIndexOf("Fred");
As with indexOf(), you can specify a location to search from as the second parameter. In this case, the string will be searched backward starting at that location. |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |