JavaScript replace()Method

String 对象参考手册JavaScript String Object

Example

In this example, we will perform a replacement. When the first "Microsoft" is found, it is replaced with "Example":

var str="Visit Microsoft! Visit Microsoft!"; var n=str.replace("Microsoft","Example");

nOutput result:

Visit Example!Visit Microsoft!

Try it yourself »

Definition and Usage

The replace() method is used to replace some characters with other characters in a string, or to replace a substring that matches a regular expression.

If you want to learn more about regular expression tutorials, please see this site's:RegExp Tutorialand ourRegExp Object Reference Manual.

This method does not change the original string.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the replace() method.


Syntax

string.replace(searchvalue,newvalue)

Parameter Values

Parameter Description
searchvalue Required. Specifies a RegExp object for the substring or pattern to be replaced.
Please note that if the value is a string, it is used as a literal text pattern to be retrieved, rather than first being converted to a RegExp object.
newvalue Required. A string value. Specifies the replacement text or a function that generates the replacement text.

Return Value

Type Description
String A new string, obtained after replacing the first match or all matches of regexp with replacement.

Technical Details

JavaScript Version: 1.2


More Examples

Example

Perform a global replacement:

var str="Mr Blue has a blue house and a blue car"; var n=str.replace(/blue/g,"red");

nOutput result:

Mr Blue has a red house and a red car

Try it yourself »

Example

Perform a global replacement, ignoring case:

var str="Mr Blue has a blue house and a blue car"; var n=str.replace(/blue/gi, "red");

nOutput result:

Mr red has a red house and a red car

Try it yourself »

Example

In this example, we add a method to JavaScript's String object through prototype to replace all "Microsoft" with "Example":

String.prototype.replaceAll = function(search, replacement) { var target = this; return target.replace(new RegExp(search, 'g'), replacement); };

Try it yourself »


String 对象参考手册JavaScript String Object

Other Extensions