Name
String.replace() — replace substring(s) matching a regular expression
Synopsis
string
.
replace
(
regexp
,
replacement
)
Arguments
regexp
The RegExp object that specifies the pattern to be replaced. If this argument is a string, it is used as a literal text pattern to be searched for; it is not first converted to a RegExp object.
replacement
A string that specifies the replacement text, or a function that is invoked to generate the replacement text. See the Description section for details.
Returns
A new string, with the first match, or all matches, of
regexp
replaced with
replacement
.
Description
replace()
performs a
search-and-replace operation on string
.
It searches string
for one or more
substrings that match regexp
and replaces
them with replacement
. If
regexp
has the global “g” attribute
specified, replace()
replaces all
matching substrings. Otherwise, it replaces only the first matching
substring.
replacement
may be a string or a
function. If it is a string, each match is replaced by the string.
Note that the $
character has
special meaning within the replacement
string. As shown in the following table, it indicates that a string
derived from the pattern match is used in the replacement.
Characters | Replacement |
---|---|
| The text that matched the 1st
through 99th parenthesized subexpression within
|
| The substring that matched
|
| The text to the left of the matched substring |
| The text to the right of the matched substring |
| A literal dollar sign |
ECMAScript v3 specifies ...
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.