Application of Replace method of string to _javascript skills

Source: Internet
Author: User
Both of these parameters are required, and the replacement of the replace () method can be a function rather than a string. In this case, each match calls the function, and the string it returns is used as the replacement text. The first parameter of the function is a string that matches the pattern. The next argument is a string that matches the subexpression in the pattern, and can have 0 or more of these parameters. The next argument is an integer that declares where the match appears in the Stringobject. The last parameter is the stringobject itself. For replacement is a function of the situation, to provide us with a great convenience.



Here's a very simple example of swapping two word sequences if you don't need repalce to do this:
Copy Code code as follows:

(function () {
var str = ' click DblClick ';
var result = Str.split (/\b/). Reverse (). Join (")
Console.log (result);
})()

It's a bit of a hassle to do this, but it's a lot more refreshing with replace processing:
Copy Code code 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--add a decimal point to a number:
Copy Code code as follows:

(function () {
var number = 12345678900;
var result = (' +number). Replace (/(\d) (? = (\d{3}) +$)/g, ' $ ');
Console.log (result);
})();


But now it's about the use of replacement as a function, so it's superfluous to change the form above into a function:
Copy Code code 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 to + ', ';
});
Console.log (result);
})();

So replace is simply to capture the matching item and then process it, replacing it as a return value, except for the function's comparison force.
Here is a more practical example, most languages have formatted output, such as the C language printf:
Copy Code code as follows:

(function () {
var str = '%s may have gone, but there be 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, the replacement is the same, and we can only in order to determine which part is replaced, if you add a paragraph, then all of the following will change. So we have to pass a variable in.
Copy Code code as follows:

(function () {
var array = [' Swallows ', ' return '];
var i = 0;
var str = '%s may have gone, but there be 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 be a time of #{how} ';
var obj = {
What: ' Swallows ',
How to: ' Return '
}
var result = Str.replace (/(?: #{(\w+)})/g,function (all,$1) {
return obj[$1];
})
Console.log (result);
})();

Obviously use the object method to be a little more reliable.

At the same time, JS is not so stringent type requirements, so,%s this form has become a limitation. Just get rid of it and replace it with a form that we can easily understand.

Disguised as a function is:
Copy Code code 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 are a time of #{how} ', {
What: ' Swallows ',
How to: ' Return '
}))
})();

The above Gsub borrowed the name of the Gsub method in prototype, although the Gsub in prototype is not used for replace, but the form is still very similar.

One of the problems now facing is:

#{what} This form of conflict problem, it is possible that the string inside just have this form of string, if not to deal with the consequences of everyone understand.

The first solution is that there are escape characters in the regular, so we can have them, so we simply add ' \ ' in front of the unwanted replacement part.

The second solution is to allow the user to customize a flag to replace the flag of #{}, thereby avoiding conflicts.

Look at the first method:
Copy Code code as follows:

(function () {
var str = ' #{what} may have gone, but there be a time of #{how},\\#{reserve} ';
function Gsub (str,replaceobj) {
Return Str.replace (/(^|.) (?: #{(\w+)})/g,function (all,$1,$2) {
if (= = ' \ ') {
Return ' #{' + $ + '} ';
}
return $ + replaceobj[$2];
})
}
Console.log (' gsub results: ', gsub (str,{
What: ' Swallows ',
How to: ' Return '
}))
})();

The above note is that ' \ ' is also an escape character in the string, and it needs to be escaped when written.

The second method:

Let's change the ' #{what} ' into a <%what%> form.
Copy Code code 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 are a time of <%how%>,#{reserve} ';
Console.log (' gsub results: ', gsub (str,{
What: ' Swallows ',
How to: ' Return '
},/(?: <% (\w+)%>)/g))
})();

Now hang the gsub on a string prototype.
Copy Code code as follows:

String.prototype.gsub = function (replaceobj,regexp) {
RegExp = RegExp | | /(^|.) (?:( #{) (\w+) (}))/g;
Return This.replace (Regexp,function (all,$1,$2,$3,$4) {
if (= = ' \ ') {
return $2+$3+$4;
}
return $ + replaceobj[$3];
})
}
var str = ' <%what%> may have gone, but there are a time of <%how%>,\\<%how%>,#{how} ';
var obj = {
What: ' Swallows ',
How to: ' Return '
}
Console.log (' Test 1: ', Str.gsub (obj,/(^|.) (?:( <%) (\w+) (%>)) (/g));
Swallows may have gone, but there are a time of return,<%how%>,#{how}
Console.log (' Test 2: ', Str.gsub (obj));
<%what%> may have gone, but there are a time of <%how%>,\<%how%>,return

Hey, seemingly and prototype in the Gsub very much like, but prototype Gsub complex, the principle is not consistent, familiar with, will be carefully analyzed prototype in the Gsub method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.