String.prototype.replace() - JavaScript | MDN

developer.mozilla.org

Tin mới

HTML: Markup language

See all HTML references

Date & time formats

See all HTML guides

CSS: Styling language

See all CSS references

See all CSS guides

Centering an element

JavaScript: Scripting language

Standard built-in objects

Expressions & operators

Statements & declarations

See all JavaScript references

Control flow & error handing

Loops and iteration

Working with objects

See all JavaScript guides

Web APIs: Programming interfaces

Service worker API

Using the Web animation API

Using the Fetch API

Working with the History API

Using the Web speech API

All web technology

Progressive web apps

Learn web development

Getting started modules

Structuring content with HTML module

CSS styling basics module

Dynamic scripting with JavaScript module

Border-image generator

Border-radius generator

Box-shadow generator

Color format converter

regular expression

Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn't have the Symbol.replace method will be coerced to a string.

RegExp.prototype[Symbol.replace]()

This method does not mutate the string value it's called on. It returns a new string.

the regular expression guide

Note: See the regular expression guide for more explanations about regular expressions.

Switching words in a string

The following script switches the words in the string. For the replacement text, the script uses capturing groups and the $1 and $2 replacement patterns.

Using an inline function that modifies the matched characters

In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on

Making a generic replacer

Suppose we want to create a replacer that appends the offset data to every matched string. Because the replacer function already receives the offset parameter, it will be trivial if the regex is statically known.

String.prototype.replaceAll()

String.prototype.match()

RegExp.prototype.exec()

RegExp.prototype.test()

Learn how to contribute

This page was last modified on Apr 12, 2026 by MDN contributors.

toLocaleLowerCase()

toLocaleUpperCase()

[Symbol.iterator]()

[Symbol.hasInstance]()

__defineGetter__()