Name
String.replace( ) — replace substring(s) matching a regular expression
Availability
JavaScript 1.2; JScript 3.0; ECMAScript v3
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 Section 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. Except,
however, 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 to be 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 ... |
Get JavaScript: The Definitive Guide, Fourth 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.