Home > Web Front-end > JS Tutorial > A brief analysis of the application of string replace method_javascript skills

A brief analysis of the application of string replace method_javascript skills

WBOY
Release: 2016-05-16 17:58:45
Original
1191 people have browsed it

Both parameters are required. The parameter replacement of the replace() method can be a function instead of a string. In this case, the function is called for each match and the string it returns is used as the replacement text. The first parameter of this function is a string matching the pattern. The next argument is a string that matches the subexpression in the pattern, and there can be 0 or more such arguments. The next parameter is an integer that declares the position in the stringObject where the match occurs. The last parameter is the stringObject itself. For the case where replacement is a function, it provides us with great convenience.



This is a very simple example of exchanging the order of two words. You can do this without repalce:

Copy code The code is as follows:

(function(){
var str = 'click dblclick';
var result = str.split(/b/ ).reverse().join('')
console.log(result);
})()

This is a little troublesome, but it is much more refreshing to use replace. :
Copy code The code is as follows:

(function(){
var str = 'click dblclick';
var result = str.replace(/b(w )(s )(w )b/,'$3$2$1');
console.log(result);
} )();

Look at another example - adding thousandths to a number:
Copy code The code is as follows:

(function(){
var number = 12345678900;
var result = ('' number).replace(/(d)(?= (d{3}) $)/g,'$1,');
console.log(result);
})();


But now The point is the use of replacement as a function, so it is unnecessary to change the above form into a function form:
Copy code The code is as follows :

(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);
})();

So replace is nothing more than capturing the match The item is then processed and replaced as a return value, which is nothing more than a comparison of functions.
Let’s look at a more practical example. Most languages ​​have formatted output, such as printf in C language:
Copy code The code is as follows:

(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);
})()

A problem here is that %s are all the same, and they are the same when replaced, and we can only judge which part is replaced according to the order. If you add a paragraph, then everything after it must be changed. . So we have to pass a variable in.
Copy code The code is as follows:

(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 the object method is more reliable.

At the same time, js does not have such strict type requirements, so the form %s has also become a limitation. Abandon it directly and replace it with a form that is easy for us to understand.

disguised as a function is:
Copy the code The code is as follows:

(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'
}))
})();

borrowed from gsub above The name of the gsub method in Prototype has been changed. Although gsub in Prototype does not use replace, it is still very similar in form.

A problem we are facing now is:

#{what} This form of conflict problem may happen to contain a string of this form. If it is not dealt with, the consequences will be Everyone knows it.

The first solution: There are escape characters in the regular expression, and we can also have them, so we simply add '' in front of the unnecessary replacement parts

The second solution : Allow users to customize a flag to replace the #{} flag to avoid conflicts.

Look at the first method:
Copy the code The code is as follows:

(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'
}))
})();

What needs to be noted above is that '' is There are also escape characters in strings, and they need to be escaped when writing.

Second method:

We replace '#{what}' with the form of <%what%>.
Copy code The code is as follows:

(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 hang gsub on the prototype of String
Copy the code The code is as follows:

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

Hehe, it seems to be very similar to gsub in Prototype, but gsub in Prototype is more complicated and the principles are inconsistent. Get familiar with it and analyze the gsub method in Prototype in detail later.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template