January 28, 2000 - Replace Method | WebReference

January 28, 2000 - Replace Method

Yehuda Shiran January 28, 2000
Replace Method
Tips: January 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

replace() is invoked as a method of a string. Its syntax is:

str.replace(regexp, replaceStr)

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");
// prints "Two One Three" under Navigator 4.0x
// prints "One Two Three" under Internet Explorer 4.0

Like exec() and 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".

Learn more about regular expressions in Column 5, JavaScript Regular Expressions.