Given the following code:
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;
}
);
};
}());
document.write('deentityify: ' + '<">'.deentityify() + '<br>');
Regarding the
function (a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
How come the anonymous function get the parameter value a, b? Of course I have tried, the output is right. Can anyone can help me?
The function is actually an argument to the ‘replace’ call. The regex matches are passed into the function as parameters.
To write the code another way, it would look:
The names of the parameters (a & b) are inconsequential and could be anything you like.
The first parameter will be the matched value and the subsequent parameters will be the values of the matched groups. So for clarity the function could be written as:
To quote MDN