In a fit of self-improvement, I'm reading (and rereading) TGP by Señor Crockford. I cannot, however, understand the middlemost part of his deentityify method.
...
return this.replace(...,
function (a, b) {
var r = ...
}
);
I think I understand that:
? r : a;
bit determines whether to return the text as is or the value of the appropriate property in entity.What I don't get at all is how the a & b are provided as arguments into function (a, b)
. What is calling this function? (I know the whole thing is self-executing, but that doesn't really clear it up for me. I guess I'm asking how is this function being called?)
If someone was interested in giving a blow by blow analysis akin to this, I'd really appreciate it, and I suspect others might too.
Here's the code for convenience:
String.method('deentityify', function ( ) {
var entity = {
quot: '"',
lt: '<',
gt: '>'
};
return function () {
return this.replace(
/&([^&;]+);/g,
function (a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
);
};
}());
a
isn't the numerical offset, it's the matched substring.
b
(in this case) is the first grouping, i.e., the match minus the surrounding &
and ;
.
The method checks to make sure the entity exists, and that it's a string. If it is, that's the replacement value, otherwise it's replaced by the original value, minus the &
and ;
The replace
function can take a function as the second parameter.
This function is then called for every match, with a signature that depends on the number of groups in the regular expression being searched for. If the regexp does not contain any capturing groups, a
will be the matched substring, b
the numerical offset in the whole string. For more details, refer to the MDN documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With