HTML and CSS Reference
In-Depth Information
and the regular expression:
/ ab[0-9]* /
If the replace() method were to substitute what is matched with an “X” :
string=string.relace(/ab[0-9]/, "X");
the resulting string would be:
"XAB"
The asterisk is a greedy metacharacter. It matches for zero or more of the preceding
characters. In other words, it attaches itself to the character preceding it; in the preced-
ing example, the asterisk attaches itself to the character class [0-9]. The matching starts
on the left, searching for ab followed by zero or more numbers in the range between 0
and 9. It is called greedy because the matching continues until the last number is found;
in this example, the number 7 . The pattern ab and all of the numbers in the range
between 0 and 9 are replaced with a single X .
Greediness can be turned off so that instead of matching on the maximum number
of characters, the match is made on the minimal number of characters found. This is
done by appending a question mark after the greedy metacharacter. See Example 17.18.
EXAMPLE 17.18
<html>
<head><title></title></head>
<body>
<script type="text/javascript">
1
var reg_expression = /\d\.?\d/;
2
var textString=prompt("Type a string of text","");
3
var result=reg_expression.test(textString); // Returns true
// or false
document.write(result+"<br />");
if (result){
document.write("<b>The regular expression /\\d\\.?\\d/
matched the string\""+textString +"\".<br />");
}
else{
alert("No Match!");
}
</script>
</body>
</html>
Search WWH ::




Custom Search