↑
Main Page
substring
var sToChange = “The sky is red. “;
alert(sToChange.replace(“red”, “blue”)); //outputs “The sky is blue.”
Here, the substring
“red”
is replaced with the string
“blue”
, making the output
“The sky is blue.”
It is possible to pass in a regular expression as the first argument as well:
var sToChange = “The sky is red.”;
var reRed = /red/;
alert(sToChange.replace(reRed, “blue”)); //outputs “The sky is blue. “
This code has the same result as the previous example, producing the output
“The sky is blue.”
You can also specify a function as the second argument of
replace()
. This function accepts one argu-
ment, the matching text, and returns the text that should replace it. For example:
var sToChange = “The sky is red.”;
var reRed = /red/;
var sResultText = sToChange.replace(reRed, function(sMatch) {
return “blue”;
});
alert(sResultText); //outputs “The sky is blue.”
In this example, the value of
sMatch
in the function is always
“red”
(because that is the only pattern
being matched). The first occurrence of
“red”
is replaced by
“blue”
because it is the value returned by
the function. Using functions to deal with text replacement in conjunction with regular expressions is
very powerful, enabling you to use all the facilities of JavaScript to determine what the replacement text
should be.
The second method is
split()
, which splits a string into a number of substrings and returns them in an
array, like this:
var sColor = “red,blue,yellow,green”;
var arrColors = sColor.split(“,”); //split at each comma
The previous code creates an array,
arrColors
, that contains four items,
“red”
,
“blue”
,
“yellow”
, and
“green”
. The same thing can be accomplished using a regular expression instead of the comma:
var sColor = “red,blue,yellow,green”;
var reComma = /\,/;
var arrColors = sColor.split(reComma); //split at each comma
Note the regular expression
reComma
requires a backslash before the comma character. The comma has
special meaning in regular expression syntax, which you don’t intend as its meaning in this case.
Note that in the previous three examples, you are replacing only the first occurrence
of
“red”
in the given string. In order to replace all occurrences, you must specify the
expression as
/red/g
.
196
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 196
Free JavaScript Editor
Ajax Editor
©
→