Easy Tutorial
❮ Dom Obj Url Prop Style Opacity ❯

JavaScript replace() Method

JavaScript String Object

Example

In this example, we will perform a replacement where the first occurrence of "Microsoft" is found and replaced with "tutorialpro":

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

n Output:

Visit tutorialpro! Visit Microsoft!

Definition and Usage

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

For more information on regular expressions, please refer to our RegExp Tutorial and RegExp Object Reference.

This method does not change the original string.


Browser Support

All major browsers support the replace() method.


Syntax

Parameter Values

Parameter Description
searchvalue Required. Specifies the substring or pattern to replace. <br>Note that if this value is a string, it is treated as a literal text pattern to search for, rather than being converted to a RegExp object first.
newvalue Required. A string value that specifies the replacement text or a function that generates the replacement text.

Return Value

Type Description
String A new string with the specified replacements made.

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");

n Output:

Mr Blue has a red house and a red car

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");

n Output:

Mr red has a red house and a red car

Example

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

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

JavaScript String Object

❮ Dom Obj Url Prop Style Opacity ❯