replace()
method returns a new string with some or all matches of a
pattern
replaced by a
replacement
.
pattern
can be a string or a
RegExp
,和
replacement
can be a string or a function to be called for each match. If
pattern
is a string, only the first occurrence will be replaced.
The original string is left unchanged.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
const newStr = str.replace(regexp|substr, newSubstr|function)
regexp
(pattern)
RegExp
object or literal. The match or matches are replaced with
newSubstr
or the value returned by the specified
function
.
substr
String
that is to be replaced by
newSubstr
. It is treated as a literal string and is
not
interpreted as a regular expression. Only the first occurrence will be replaced.
newSubstr
(replacement)
String
that replaces the substring specified by the specified
regexp
or
substr
parameter. A number of special replacement patterns are supported; see the "
Specifying a string as a parameter
" section below.
function
(replacement)
regexp
or
substr
. The arguments supplied to this function are described in the "
Specifying a function as a parameter
" section below.
A new string, with some or all matches of a pattern replaced by a replacement.
This method does not change the calling
String
object. It simply returns a new string.
To perform a global search and replace, include the
g
switch in the regular expression.
The replacement string can include the following special replacement patterns:
| Pattern | 插入 |
|---|---|
$$
|
Inserts a
"$"
.
|
$&
|
Inserts the matched substring. |
$`
|
Inserts the portion of the string that precedes the matched substring. |
$'
|
Inserts the portion of the string that follows the matched substring. |
$
n
|
Where
n
is a positive integer less than 100, inserts the
n
th parenthesized submatch string, provided the first argument was a
RegExp
object. Note that this is
1
-indexed. If a group
n
is not present (e.g., if group is 3), it will be replaced as a literal (e.g.,
$3
).
|
$<Name>
|
Where
Name
is a capturing group name. If the group is not in the regular expressions (or not in the match), this will resolve to the empty string. Only available in browser versions supporting named capturing groups.
|
You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. ( 注意: The above-mentioned special replacement patterns do not apply in this case.)
Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.
The arguments to the function are as follows:
| Possible name | Supplied value |
|---|---|
match
|
The matched substring. (Corresponds to
$&
above.)
|
p1, p2, ...
|
n
th string found by a parenthesized capture group (including named capturing groups), provided the first argument to
replace()
was a
RegExp
object. (Corresponds to
$1
,
$2
, etc. above.) For example, if
/(\a+)(\b+)/
, was given,
p1
is the match for
\a+
,和
p2
for
\b+
.
|
offset
|
The offset of the matched substring within the whole string being examined. (For example, if the whole string was
'abcd'
, and the matched substring was
'bc'
, then this argument will be
1
.)
|
string
|
The whole string being examined. |
groups
|
In browser versions supporting named capturing groups, will be an object whose keys are the used group names, and whose values are the matched portions (
undefined
if not matched).
|
(The exact number of arguments depends on whether the first argument is a
RegExp
object—and, if so, how many parenthesized submatches it specifies.)
The following example will set
newString
to
'abc - 12345 - #$*%'
:
function replacer(match, p1, p2, p3, offset, string) {
// p1 is nondigits, p2 digits, and p3 non-alphanumerics
return [p1, p2, p3].join(' - ');
}
let newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString); // abc - 12345 - #$*%
In the following example, the regular expression is defined in
replace()
and includes the ignore case flag.
let str = 'Twas the night before Xmas...'; let newstr = str.replace(/xmas/i, 'Christmas'); console.log(newstr); // Twas the night before Christmas...
This logs
'Twas the night before Christmas...'
.
注意: 见 this guide for more explanations about regular expressions.
Global replace can only be done with a regular expression. In the following example, the regular expression includes the
global and ignore case flags
which permits
replace()
to replace each occurrence of
'apples'
in the string with
'oranges'
.
let re = /apples/gi; let str = 'Apples are round, and apples are juicy.'; let newstr = str.replace(re, 'oranges'); console.log(newstr); // oranges are round, and oranges are juicy.
This logs
'oranges are round, and oranges are juicy'
.
The following script switches the words in the string. For the replacement text, the script uses
capturing groups
和
$1
and
$2
replacement patterns.
let re = /(\w+)\s(\w+)/; let str = 'John Smith'; let newstr = str.replace(re, '$2, $1'); console.log(newstr); // Smith, John
This logs
'Smith, John'
.
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 the matched item before it is given back as a replacement.
The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.
function styleHyphenFormat(propertyName) {
function upperToHyphenLower(match, offset, string) {
return (offset > 0 ? '-' : '') + match.toLowerCase();
}
return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
Given
styleHyphenFormat('borderTop')
, this returns
'border-top'
.
Because we want to further transform the
result
of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the
toLowerCase()
method. If we had tried to do this using the match without a function, the
toLowerCase()
would have no effect.
let newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase()); // won't work
This is because
'$&'.toLowerCase()
would first be evaluated as a string literal (resulting in the same
'$&'
) before using the characters as a pattern.
The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with
"F"
. The function returns the Celsius number ending with
"C"
. For example, if the input number is
"212F"
, the function returns
"100C"
. If the number is
"0F"
, the function returns
"-17.77777777777778C"
.
The regular expression
test
checks for any number that ends with
F
. The number of Fahrenheit degree is accessible to the function through its second parameter,
p1
. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the
f2c()
函数。
f2c()
then returns the Celsius number. This function approximates Perl's
s///e
标志。
function f2c(x) {
function convert(str, p1, offset, s) {
return ((p1 - 32) * 5/9) + 'C';
}
let s = String(x);
let test = /(-?\d+(?:\.\d*)?)F\b/g;
return s.replace(test, convert);
}
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'String.prototype.replace' in that specification. |
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
更新 GitHub 上的兼容性数据| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
replace
|
Chrome 1 | Edge 12 | Firefox 1 | IE 4 | Opera 4 | Safari 1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 | nodejs 0.1.100 |
完整支持
String.prototype.replaceAll()
String.prototype.match()
RegExp.prototype.exec()
RegExp.prototype.test()
String
String.fromCharCode()
String.fromCodePoint()
String.prototype.anchor()
String.prototype.big()
String.prototype.blink()
String.prototype.bold()
String.prototype.charAt()
String.prototype.charCodeAt()
String.prototype.codePointAt()
String.prototype.concat()
String.prototype.endsWith()
String.prototype.fixed()
String.prototype.fontcolor()
String.prototype.fontsize()
String.prototype.includes()
String.prototype.indexOf()
String.prototype.italics()
String.prototype.lastIndexOf()
String.prototype.link()
String.prototype.localeCompare()
String.prototype.match()
String.prototype.matchAll()
String.prototype.normalize()
String.prototype.padEnd()
String.prototype.padStart()
String.prototype.repeat()
String.prototype.replace()
String.prototype.replaceAll()
String.prototype.search()
String.prototype.slice()
String.prototype.small()
String.prototype.split()
String.prototype.startsWith()
String.prototype.strike()
String.prototype.sub()
String.prototype.substr()
String.prototype.substring()
String.prototype.sup()
String.prototype.toLocaleLowerCase()
String.prototype.toLocaleUpperCase()
String.prototype.toLowerCase()
String.prototype.toSource()
String.prototype.toString()
String.prototype.toUpperCase()
String.prototype.trim()
String.prototype.trimEnd()
String.prototype.trimStart()
String.prototype.valueOf()
String.prototype[@@iterator]()
String.raw()
Function
Object
Object.prototype.__defineGetter__()
Object.prototype.__defineSetter__()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Object.prototype.toSource()
Object.prototype.toString()
Object.prototype.valueOf()
Object.setPrototypeOf()