0

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: ' + '&lt;&quot;&gt;'.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?

Spontifixus
6,6709 gold badges48 silver badges64 bronze badges
asked Feb 6, 2013 at 11:55

2 Answers 2

3

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:

function match(a, b) {
 var r = entity[b];
 return typeof r === 'string' ? r : a;
}
var result = this.replace(/&([^&;]);/g, match)

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:

function matchFn(match, group1, group2, group3) {
 var r = entity[group1];
 return typeof r === 'string' ? r : match;
}

To quote MDN

A function to be invoked to create the new substring (to put in place of the substring received from parameter #1). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.

answered Feb 6, 2013 at 12:02
Sign up to request clarification or add additional context in comments.

1 Comment

and don't forget that they don't have to be called a and b - you can call those parameters whatever you want.
1

You can handover a function as second parameter to replace(). This function acts as some kind of callback function and receives it's parameters from the calling replace in a fixed order like stated in the Docs.

a and b are just arbitrary names - a is the matched substring and b the capture group ([^&;]).

answered Feb 6, 2013 at 12:03

2 Comments

what exactly is a "static parameter"? That's a very confusing term.
@Alnitak I meant static/fixed order. Rephrased to hopefully be more clear.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.