HTML and CSS Reference
In-Depth Information
Figure 17.7 The search() method found the pattern starting at character position
2, where 0 is the beginning character.
17.3.3 The replace() Method
The replace() method is used to search for a string and replace the string with another
string. The i modifier is used to turn off case sensitivity and the g modifier makes the
replacement global; that is, all occurrences of the found pattern are replaced with the
new string. The replace() method is also used with the grouping metacharacters. (See
the section “Grouping or Clustering” on page 761.)
FORMAT
string = oldstring.replace(regular_expression, replacement_value);
EXAMPLE
var str1 = "I am feeling blue".replace(/blue/, "upbeat");
( str1 is assigned: "I am feeling upbeat.")
EXAMPLE 17.7
<html>
<head>
<title>The replace() Method</title>
</head>
<body bgcolor="yellow">
<script type = "text/javascript">
1
var myString="Tommy has a stomach ache."
2
var regex = /tom/i; // Turn off case sensitivity
3
var newString=myString.replace(regex, "Mom");
document.write(newString +"<br />");
</script>
</body>
</html>
EXPLANATION
1
The variable called myString is assigned the string “Tommy has a stomach ache.”
Note that the pattern Tom or tom is found in the string twice.
2
The variable called regex is assigned the regular expression /tom/i. The i modifier
turns off the case sensitivity. Any combination of uppercase and lowercase letters
in the pattern tom will be searched for within the string.
 
 
Search WWH ::




Custom Search