Crockford Research Method - Page 41 of The Good Parts

In a fit of self-improvement, I read (and re-read) TGP Señor Crockford. However, I cannot understand the middle part of his deentityify method.

... return this.replace(..., function (a, b) { var r = ... } ); 

I think I understand that:

  • this.replace is passed two arguments: a regular expression as the search value and a function to generate the replacement value;
  • b is used to access the properties of an entity object;
  • bit return ? r : a; ? r : a; determines whether to return the text as is or the value of the corresponding property in the entity.

What I am not getting at all is how a and b are provided as arguments to function (a, b) . What is called this function? (I know that all this is self-fulfillment, but in fact it is not entirely clear to me. I’m probably asking what this function is called?)

If someone is interested in giving a shock analysis similar to this one , I would really appreciate it, and I suspect others may too.

Here is 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; } ); }; }()); 
+4
source share
2 answers

a is not a numerical offset, but a substring match .

b (in this case) is the first grouping, that is, a coincidence minus the surrounding & and ; .

The method checks if the entity exists and that it is a string. If so, then the replacement value, otherwise it will be replaced by the original value, minus & and ;

+5
source

The replace function can take a function as a second parameter.

This function is then called for each match with a signature, which depends on the number of groups in the regular expression that needs to be found. If regexp does not contain capture groups, a will be a matched substring, b numeric offset in the entire string. See the documentation for more information.

+5
source

Source: https://habr.com/ru/post/1412244/


All Articles