HTML and CSS Reference
In-Depth Information
EXAMPLE
17.24
<html>
<head><title>Greed</title></head>
<body bgcolor="lightblue">
<script type="text/javascript">
1
var myString="abcdefghijklmnopqrstuvwxyz";
document.write("<b>Old string:</b>"+myString+"<br />");
2
myString=myString.replace(/[a-z]+/, "XXX")
;
3
document.write("<b>New string:<b> "+ myString+"<br />");
</script>
</body>
</html>
EXPLANATION
1
The variable, called
myString
, is assigned a string of lowercase letters.
2
The regular expression reads: Search for one or more lowercase letters, and re-
place them with
XXX
. The + metacharacter is greedy. It takes as many characters
as match the expression; that is, it starts on the left side of the string, grabbing as
many lowercase letters as it can find until the end of the string.
3
The value of
myString
is printed after the substitution, as shown in Figure 17.26.
Figure 17.26
The + sign is greedy. One or more lowercase letters are replaced with
XXX
; that is, the whole string.
EXAMPLE
17.25
<html>
<head><title></title></head>
<body>
<script type="text/javascript">
1
var myString="abcdefghijklmnopqrstuvwxyz";
document.write("<font size='+1'>Old string: <b>"
+myString+"<br />");
2
myString=
myString.replace(/[a-z]+?/, "XXX"
);
document.write("</b>New string: <b>"+myString+"<br />");
</script>
</body>
</html>