--- title: String.prototype.replace() slug: Web/JavaScript/Reference/Global_Objects/String/replace translation_of: Web/JavaScript/Reference/Global_Objects/String/replace ---
Phương thức replace()
sẽ trả về một chuỗi mới với một vài (hoặc tất cả) phần tử trùng khớp với pattern
được thay thế bằng replacement
. Pattern có thể là một chuỗi, hoặc một {{jsxref("RegExp")}}, và replacement có thể là một chuỗi, hoặc một function được gọi áp dụng cho mỗi kết quả trùng khớp. Nếu pattern là một chuỗi, thì phương thức replace() chỉ trả về kết quả đầu tiên trùng khớp.
Replace() không làm thay đổi chuỗi gốc.
const newStr = str.replace(regexp|substr, newSubstr|function)
regexp
(pattern)newSubstr
hoặc giá trị trả về bởi function
.substr
newSubstr
. String này sẽ được xem như là một literal string và không phải là một regular expression. Nên chỉ có phần tử trùng khớp đầu tiên sẽ bị thay thế.newSubstr
(replacement)regexp
hoặc substr
. Có nhiều kiểu thay thế khác nhau, xem chi tiết tại phần "Specifying a string as a parameter" bên dưới.function
(replacement)Một string mới, với một số phần tử trùng khớp (hoặc tất cả phần tử trùng khớp) đã bị thay thế bởi các replacement.
Phương thức này không làm thay đổi {{jsxref("String")}} gốc. Nó chỉ đơn giản tạo ra một string mới.
Để thực hiện tìm kiếm global search và replace, hãy thêm từ khóa g
và biểu thức regular expression.
The replacement string can include the following special replacement patterns:
Pattern | Inserts |
---|---|
$$ |
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 {{jsxref("RegExp")}} object. Note that this is 1 -indexed. |
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. (Note: 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, ... |
The nth string found by a parenthesized capture group, provided the first argument to replace() was a {{jsxref("RegExp")}} object. (Corresponds to $1 , $2 , etc. above.) For example, if /(\a+)(\b+)/ , was given, p1 is the match for \a+ , and 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. |
(The exact number of arguments depends on whether the first argument is a {{jsxref("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 - #$*%
Ví dụ bên dưới, regular expression được định nghĩa trong replace()
và nó có thêm flat "i" (giúp kết quả matching không phân biệt chữ hoa và chữ thường).
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...'
.
Note: See this guide for more explanations about regular expressions.
Global replace (thay thế tất cả kết quả trùng khớp) có thể được thực hiện trong regex. Ví dụ sau, biểu thức regex có chứa các flag global and ignore case flags cho phép replace()
sẽ thay thế mỗi string 'apples'
trong chuỗi gốc với string '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'
.
Đoạn code bên dưới sẽ đảo qua lại vị trí của các từ trong một string. Ở phần replacement, đoạn code sử dụng capturing groups và ký tự $1,$2
để làm pattern cho phần replacement.
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'
.
Trong ví dụ này, tất cả trường hợp chữ cái viết hoa trong một string sẽ được convert sang dạng viết thường, và dấu gạch ngang sẽ được thêm vào trước vị trí matching đó. Điều quan trọng ở đây, là cần thêm vào các dấu gạch ngang này trước khi trả về một replacement hoàn chỉnh để sử dụng.
Replacement function này sẽ nhận vào các đoạn trích mà đã match với pattern làm tham số, và sử dụng các đoạn trích đó để biến đổi chữ hoa chữ thường, và ghép nối một dấu gạch ngang vào trước mỗi đoạn trích.
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 {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} method. If we had tried to do this using the match without a function, the {{jsxref("String.prototype.toLowerCase()", "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()
function. f2c()
then returns the Celsius number. This function approximates Perl's s///e
flag.
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); }
Specification |
---|
{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}} |
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.
{{Compat("javascript.builtins.String.replace")}}