0

Given this Javascript:

String.method('deentityify', function () {
    // The entity table.  It maps entity names to
    // characters.
    var entity = {
        quot: '"',
        lt: '<',
        gt: '>'
    };

    // Return the deentityify method
    return function () {

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

document.writeln('&lt;&quot;&gt;'.deentityify());

What goes into the last function as a and b, and why?

I get that we're splitting up the string I'm passing in into 3 groups, but I don't understand why &lt; is going into a and why just lt is going into b.

1

1 Answer 1

2

The first argument contains the whole match, all consecutive arguments are the matched groups. The last two arguments are the offset and full input string.

var input = '&lt;&quot;&gt;'
input.replace( /&([^&;]+);/g, function (a, b)

The pattern matches all occurrences of & + every non-& + ;.

a      b
&lt;   lt 
&quot; quot
&gt;   gt

See also: MDN: String.replace with a function

Sign up to request clarification or add additional context in comments.

5 Comments

So, the first match is &lt; right? Where does the lt come from? Sorry - I know I'm being dense.
lt are all non-& characters between the & and the ;. It is captured by the parens.
Argh. I'm still not getting it. I don't understand why we're passing two things per match. It seems to me that we're only matching 3 things: &lt; &quot; &gt; Are we really capturing 6 things?
@TerryDonaghe The parens create a new group. a contains the full match and b the first group. The pattern is found three time, and since you've added the g (global) flag to the RegEx, the function is called three times, with a and b as specified in my answer.
Thanks @Rob W! I think I've finally got it. I looked at the doc link you provided and that helps. My brain hurts.

Your Answer

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.