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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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");
document.write(str);
// 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.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business