Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript replace() method

JavaScript replace() method

String Object Reference JavaScript String object

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

Internet ExplorerFirefoxOperaGoogle ChromeSafari

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 »


String Object Reference JavaScript String object