Crockford's deentityify method - p.41 of The Good Parts
function, javascript, module
Solution
`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 `;`
Problem
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: - this.replace is passed two arguments, the regex as the search value and the function to generate the replacement value; - the b is used to access the properties in the entity object; - 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; } ); }; }()); ```