Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 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;
            }
        );
    };
}()); 
like image 846
Nick Avatar asked Dec 28 '22 00:12

Nick


2 Answers

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 ;

like image 162
Dave Newton Avatar answered Dec 31 '22 13:12

Dave Newton


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.

like image 34
phihag Avatar answered Dec 31 '22 15:12

phihag