Easy Tutorial
❮ Jsref Ln2 Dom Obj Map ❯

JavaScript replaceAll() Method

JavaScript String Object

Example

In this example, we will replace all occurrences of "Microsoft" with "tutorialpro":

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

n Output:

Visit tutorialpro! Visit tutorialpro!

Definition and Usage

The replaceAll() method is used to replace some characters with others in a string, or to replace substrings that match a regular expression. This function replaces all occurrences of the matched substring.

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

This function is not supported in Internet Explorer on PC.


Syntax

const newStr = str.replaceAll(regexp|substr, newSubstr|function)

Parameter Values

Parameter Description
regexp|substr Required. Specifies the substring or a RegExp object for the pattern to be replaced. <br>Note that if this value is a string, it is treated as a literal text pattern to be searched for, rather than being converted to a RegExp object. When using a regex, you must set the global ("g") flag, <br>otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".
newSubstr|function 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 all matches of regexp replaced by newSubstr.

Technical Details

| JavaScript Version: | 1.2 | | --- | --- |


More Examples

Example

Performing a global replacement:

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

n Output:

Mr red has a red house and a red car.

JavaScript String Object

❮ Jsref Ln2 Dom Obj Map ❯