Javascript - String replace() Method

The replace() method matches a string for a specified value, or a regular expression, and returns a new string whose the values are replaced.

Description

The replace() method matches a string for a specified value, or a regular expression, and returns a new string whose the values are replaced.

If you are replacing a value and not a regular expression, only the first instance of the value will be replaced.

To replace all occurrences of a specified value, use the global (g) modifier.

This method does not change the original string.

Syntax

string.replace(searchvalue, newvalue)

Parameter Values

Parameter Require Description
searchvalue Required. The value, or regular expression, that will be replaced by the new value
newvalueRequired.The value to replace the search value with

Return

A new String, where the specified value(s) has been replaced by the new value

Example

Return a string where "t" is replaced with "d":

It only replaces the first t.

Demo

//replace "t" with "d" in the string below:
var str = "this is a test";
var res = str.replace("t", "d");
console.log(res);//from w w  w.  ja v  a2  s  .c o  m
//Perform a global replacement:
//replace "blue" with "red" in the paragraph below:
var str = "blue blue blue test test test";
var res = str.replace(/blue/g, "red");
console.log(res);

//Perform a global, case-insensitive replacement:
//replace "blue" with "red" in the paragraph below:
var str = "BLUE blue BLue bLue test BLuE";
var res = str.replace(/blue/gi, "red");
console.log(res);

//Using a function to return the replacement text:
//set "blue", "house" and "car" to upper-case
var str = "blue Blue Hourse house House Car car caR";
var res = str.replace(/blue|house|car/gi, function (x) {
    return x.toUpperCase();
});
console.log(res);

Result