Main Page


var sToChange = “The sky is red. “;
alert(sToChange.replace(“red”, “blue”)); //outputs “The sky is blue.”
Here, the substring
is replaced with the string
, 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
. 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
in the function is always
(because that is the only pattern
being matched). The first occurrence of
is replaced by
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
, 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,
, that contains four items,
, and
. 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
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
in the given string. In order to replace all occurrences, you must specify the
expression as
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 196

JavaScript EditorFree JavaScript Editor     Ajax Editor