January 28, 2000 - Replace Method
January 28, 2000|
Tips: January 2000
Yehuda Shiran, Ph.D.
replace()is invoked as a method of a string. Its syntax is:
regexp is the name of a regular expression. You can supply it as a literal or as a variable.
str is any string.
This method is equivalent to Perl's
s/// operator. The following script swaps the first two words in a string:
var str = "One Two Three".replace(/^([^ ]+) +([^ ]+)/, "$2 $1"); document.write(str); // prints "Two One Three"
Notice the variable interpolation that takes place. As opposed to Perl, it doesn't matter if you use double-quotes or single-quotes for the second argument. The replacement string undergoes variable interpolation each time the pattern matches. Note that only Perl-like variables
($...) are interpolated in the replacement string. You can also embed other variables in the string, but they are not interpolated each time the pattern matches. Here's an example:
var company = "Digital"; var str = "Intel is a chip manufacturer!"; var newstr = str.replace(/Intel is/, company + " is"); document.write(newstr); // prints "Digital is a chip manufacturer!"
Note that only in Navigator 4.0x the regular expression can also be enclosed in ordinary quotes:
var str = "One Two Three".replace("^([^ ]+) +([^ ]+)", "$2 $1"); document.write(str); // prints "Two One Three" under Navigator 4.0x // prints "One Two Three" under Internet Explorer 4.0
match(), this method updates the RegExp object's properties.
If you want to enable multiple replacements, the regular expression should utilize a /g modifier:
var str = "Car Car Car"; var newstr = str.replace(/Car/g, "Bus"); document.write(newstr); // prints "Bus Bus Bus"
If you do not include this modifier, only the first match is replaced with the alternative string, so the preceding script would print
"Bus Car Car".