JavaScript replace() method
Example
In this example, we perform a replacement where the first "Microsoft" found is replaced with "Runoob":
var
str
=
"
Visit Microsoft! Visit Microsoft!
"
;
var
n
=
str
.
replace
(
"
Microsoft
"
,
"
Runoob
"
)
;
n Output result:
Visit Runoob!Visit Microsoft!
Try it »
Definition and Usage
The replace() method replaces some characters with others in a string, or replaces a substring that matches a regular expression.
If you want to learn more about regular expressions, please see our:RegExp Tutorial and our RegExp Object Reference Manual.
This method does not change the original string.
Browser support





All major browsers support the replace() method.
Syntax
string
.replace(
searchvalue,newvalue
)
Parameter value
| Parameters | Description |
|---|---|
| searchvalue | Required. Specifies a substring or a RegExp object for the pattern to replace. |
| Note that if this value is a string, it is treated as a literal text pattern to search for, rather than being first converted to a RegExp object. | |
| newvalue | Required. A string value. Specifies the replacement text or a function that produces it. |
Return Value
| Type | Description |
|---|---|
| String | A new string resulting from replacing the first 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
"
)
;
n Output result:
Mr Blue has a red house and a red car
Try it »
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 result:
Mr red has a red house and a red car
Try it »
Example
In this example, we add a method to the JavaScript String object via prototype to replace all "Microsoft" with "Runoob":
String
.
prototype
.
replaceAll
=
function
(
search
,
replacement
)
{
var
target
=
this
;
return
target
.
replace
(
new
RegExp
(
search
,
'
g
'
)
,
replacement
)
;
}
;
Try it »
JavaScript String object