简体   繁体   中英

How do the arguments to String#replace's callback get set?

var ourData = '<h1><%= myProperty %></h1>';
var instance = this;
return ourData.replace(/<%=\s+(.*?)\s+%>/g, function (m, m1) {
    return instance.model[m1]; 
    // Here m1 is set to "<%= myProperty %>" and m1 is set to "myProperty"
    // FYI, model[m1] is "Hello World"
});

I just cant understand the logic how m and m1 gets the values "<%= myProperty %>" and "myProperty" respectively.

Could someone please explain to me how this parameters gets the values they get and what is the logic behind it?

Thanks in advance.

When you call String#replace passing in a function as the second argument, replace will call that function for matches it finds. (It'll make one call for the first match if the regex doesn't have the g flag, or one call for each match if — like yours — it does.)

Each time replace calls the callback, the first argument it provides is the entire matched string (the entire string that matched your expression). Then it gives the values of any capture groups you've defined in the regex as subsequent arguments after that, in order.

In your case, your regular expression as a whole matches <%= myProperty %> , and the capture group you have in the expression matches myProperty .

Completely subjective, but I tend to use the argument names m and then c0 , c1 , etc., to remind myself what I'm dealing with. m = "match", and of course c0 is the first capture group, etc.

A slightly simpler example may help: Live Copy

var str = "mumble x123 blah x234 mumfff x345";

console.log("String: '" + str + "'");
str = str.replace(/x(\d+)/g, function(m, c0) {
    console.log("m = '" + m + "', c0 = '" + c0 + "'");
    return "y" + c0;
});
console.log("Result: '" + str + "'");

When we run that, we get:

String: 'mumble x123 blah x234 mumfff x345'
m = 'x123', c0 = '123'
m = 'x234', c0 = '234'
m = 'x345', c0 = '345'
Result: 'mumble [123] blah [234] mumfff [345]'

...because the regular expression as a whole matches an x followed by one or more digits, and we're using a capture group to get those digits (and then returning a replacement that puts those digits in [] , leaving off the x ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM