Java Reference
In-Depth Information
If you put this all together in an example, you have the following:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script language=”JavaScript” type=”text/JavaScript”>
var myString = “Paul, Paula, Pauline, paul, Paul”;
var myRegExp = /Paul/;
myString = myString.replace(myRegExp, “Ringo”);
alert(myString);
</script>
</body>
</html>
If you load this code into a browser, you will see the screen shown in Figure 9-3.
Figure 9-3
You can see that this has replaced the fi rst occurrence of Paul in your string. But what if you wanted all
the occurrences of Paul in the string to be replaced? The two at the far end of the string are still there,
so what happened?
By default, the RegExp object looks only for the fi rst matching pattern, in this case the fi rst Paul , and then
stops. This is a common and important behavior for RegExp objects. Regular expressions tend to start at
one end of a string and look through the characters until the fi rst complete match is found, then stop.
What you want is a global match, which is a search for all possible matches to be made and replaced. To
help you out, the RegExp object has three attributes you can defi ne. You can see these listed in the follow-
ing table.
Attribute Character
Description
G
Global match. This looks for all matches of the pattern rather than stop-
ping after the fi rst match is found.
I
Pattern is case-insensitive. For example, Paul and paul are considered the
same pattern of characters.
M
Multi-line fl ag. Only available in IE 5.5+ and NN 6+, this specifi es that the
special characters ^ and $ can match the beginning and the end of lines as
well as the beginning and end of the string. You'll learn about these char-
acters later in the chapter.
Search WWH ::




Custom Search