简体   繁体   中英

Crockford's deentityify method - p.41 of The Good Parts

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:

  1. this.replace is passed two arguments, the regex as the search value and the function to generate the replacement value;
  2. the b is used to access the properties in the entity object;
  3. the return ? r : a; ? 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;
            }
        );
    };
}()); 

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 .

a isn't the numerical offset, it's the matched substring .

b (in this case) is the first grouping, ie, 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 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