According to W3C instructions, the string object's replace method is called stringobject. Replace (Regexp/substr, replacement ).
Both parameters are required. The replacement parameter of the Replace () method can be a function rather than a string. In this case, each match calls this function, and the string it returns will be used as the replacement text. The first parameter of this function is a matching string. The following parameter is a string that matches the subexpression in the pattern. There can be 0 or more such parameters. The following parameter is an integer that declares the position where the matching occurs in the stringobject. The last parameter is stringobject itself. Replacement is a function, which provides us with great convenience.
Here is an example of switching the order of two words. You can do this without using repalce:
(function(){
var str = 'click dblclick';
var result = str.split(/\b/).reverse().join('')
console.log(result);
})()
This is a little troublesome, and it seems much more refreshing to use replace:
(function(){
var str = 'click dblclick';
var result = str.replace(/\b(\w+)(\s+)(\w+)\b/,'$3$2$1');
console.log(result);
})();
Let's look at another example -- add a sub-digit to the number:
(function(){
var number = 12345678900;
var result = (''+number).replace(/(\d)(?=(\d{3})+$)/g,'$1,');
console.log(result);
})();
But now we need to use replacement as a function. Therefore, we need to change the above form to the function form:
(function(){
var str = 'click dblclick';
var result = str.replace(/\b(\w+)(\s+)(\w+)\b/,function(all,$1,$2,$3){
return $3+$2+$1;
});
console.log(result);
})();
(function(){
var number = 12345678900;
var result = (''+number).replace(/(\d)(?=(\d{3})+$)/g,function(all,$1){
return $1 + ',';
});
console.log(result);
})();
Therefore, replace is nothing more than capturing and processing matched items and replacing them as return values, but it is a powerful function.
The following is a practical example. Most languages have formatted output, such as the C language printf:
(function(){
var str = '%s may have gone, but there is a time of %s';
var result = str.replace(/(%s)/g,function(){
return 'replacement';
})
console.log(result);
})()
The problem here is that % s is the same, and the replacement is the same, and we can only judge which part is replaced in order. If a segment is added, then all the subsequent changes will be made. So we have to pass in a variable.
(function(){
var array = ['Swallows','return'];
var i = 0;
var str = '%s may have gone, but there is a time of %s';
var result = str.replace(/(%s)/g,function(){
return array[i++];
})
console.log(result);
})();
(function(){
var str = '#{what} may have gone, but there is a time of #{how}';
var obj = {
what : 'Swallows',
how : 'return'
}
var result = str.replace(/(?:#{(\w+)})/g,function(all,$1){
return obj[$1];
})
console.log( result);
})();
Obviously, it is more reliable to use object methods.
At the same time, JS does not have such strict type requirements, so the form of % s has become a limitation. Instead, we can easily understand it.
Disguised as a function:
(Function (){
Function gsub (STR, replaceobj ){
Return Str. Replace (/(? : # {(\ W +)})/g, function (all, $1 ){
Return replaceobj [$1];
})
}
Console. Log ('gsub result: ', gsub (' # {What} may have gone, but there is a time of # {how }',{
What: 'swallows ',
How: 'Return'
}))
})();
The above gsub borrow the name of the gsub method in prototype. Although the gsub in prototype is not a replace, it is still similar in form.
One problem is:
# {What} conflicts in this form. It is possible that strings in this form are exactly in the string. If this form is not processed, you will understand the consequences.
Solution 1: the regular expression contains escape characters, so we can also add '\' before the unneeded replacement '\'
Solution 2: allow the user to customize a flag to replace the # {} flag to avoid conflict.
See the first method:
(Function (){
VaR STR = '# {What} may have gone, but there is a time of # {how}, \\# {reserve }';
Function gsub (STR, replaceobj ){
Return Str. Replace (/(^ | .)(? : # {(\ W +)})/g, function (all, $1, $2 ){
If ($1 = '\\'){
Return '# {' + $2 + '}';
}
Return $1 + replaceobj [$2];
})
}
Console. Log ('gsub result: ', gsub (STR ,{
What: 'swallows ',
How: 'Return'
}))
})();
Note that '\' is also an escape character in the string and must be escaped during writing.
Method 2:
Replace '# {What}' with <% What %>.
(Function (){
Function gsub (STR, replaceobj, Regexp ){
Regexp = Regexp | /(? : # {(\ W +)})/g;
Return Str. Replace (Regexp, function (all, $1 ){
Return replaceobj [$1];
})
}
VaR STR = '<% What %> may have gone, but there is a time of <% How %>, # {reserve }';
Console. Log ('gsub result: ', gsub (STR ,{
What: 'swallows ',
How: 'Return'
},/(? : <% (\ W +) %>)/g ))
})();
Now we can mount gsub to the string prototype.
String. Prototype. gsub = function (replaceobj, Regexp ){
Regexp = Regexp |/(^ | .)(? :( # {) (\ W +) (})/g;
Return this. Replace (Regexp, function (all, $1, $2, $3, $4 ){
If ($1 = '\\'){
Return $2 + $3 + $4;
}
Return $1 + replaceobj [$3];
})
}
VaR STR = '<% What %> may have gone, but there is a time of <% How %>, \\< % How %>, # {how }';
VaR OBJ = {
What: 'swallows ',
How: 'Return'
}
Console. Log ('test 1: ', str. gsub (OBJ,/(^ | .)(? :( <%) (\ W +) (%>)/g ));
// Swallows may have gone, but there is a time of return, <% How %>, # {how}
Console. Log ('test 2: ', str. gsub (OBJ ));
// <% What %> may have gone, but there is a time of <% How %>, \ <% How %>, return
Hey, it seems like gsub in prototype. However, gsub in prototype is a little more complex and has different principles. You should be familiar with it and carefully analyze the gsub method in prototype.