Replace () returns a new string that replaces some or all of the pattern matches with the replacement value. The pattern can be a string or a regular expression, and the replacement value can be a string or a callback function that is called on every match. If pattern is a string, only the first match is replaced.
var str = 'abb';
var res = str.replace('b'.'c'); // replace does not have global matching capability
console.log(res); // acb
Copy the code
When the reaplce method is used with the re:
var str = 'abb';
var reg = /b/g; // add g global match here
var res = str.replace(reg, 'c');
console.log(res); // acc
Copy the code
When the replace method takes the second argument as a function: the first argument $represents the whole of the match (aABB CCDD), the second argument represents the first subexexpression (ac), the third argument represents the second subexexpression (b d), and so on when there is a fourth argument, and the fifth argument…
var str = 'aabbccdd';
var reg = /(\w)\1(\w)\2/g;
var res = str.replace(reg, function ($, $1, $2) {
// console.log($, $1, $2);
// aabb, a, b ccdd, c, d
return $2 + $2 + $1 + $1;
});
console.log(res); // bbaaddcc
Copy the code