HTML and CSS Reference
In-Depth Information
EXPLANATION ( CONTINUED )
6
The charAt() method returns the character found at a specified position within a
string; in this example, position 0. Position 0 is the first character in the string, a
letter D .
7
By giving the charAt() method the length of the string minus 1, the last character
in the string is extracted, a letter g (see Figure 9.34).
Figure 9.34 The charAt() , split() , and substr() methods: Output from Example 9.29.
Search and Replace Methods. In word processing software you'll always find
some mechanism to search for patterns in strings and to replace one string with another.
JavaScript provides methods to do the same thing, using the String object. The search()
method searches for a substring and returns the position where the substring is found
first. The match() method searches a string for substrings and returns an array contain-
ing all the matches it found. The replace() method searches for a substring and replaces
it with a new string. These methods are discussed again in Chapter 17, “Regular Expres-
sions and Pattern Matching,” in more detail.
EXAMPLE 9.30
<html>
<head><title>Search and Replace</title></head>
<body bgcolor=lightgreen>
<font face="arial" size="+1">
Search and Replace Methods<br />
<small>
<script type="text/javascript">
1
var straddr = "DanielSavage@dadserver.org";
document.write("The original string is "+ straddr
+ "<br />");
document.write( "The new string is "+
2
straddr.replace("Daniel","Jake") +"<br />");
3
var index=straddr.search("dad");
 
Search WWH ::




Custom Search