0
function function1(format) {
        var regexp = /[<>]/g;
                                       //Here the parameters are matched string,
                                       //the position and the original text
        var str = format.replace(regexp,function(match,position,originalText){
            return match;
        });
        return str;
}

function function2(format) {
    var regexp = /:(\w+)/g;
                                    //Here the parameters are matched string, 
                                    //something like stripped string, and the position
    var str = format.replace(regexp,function(match,stripped,position){
        return match;
    });
    return str;
}

console.log(function1('<hello>'));
console.log(function2(':url :method'));

I got the first function from #Professional JavaScript for Web Developers#, and the second function from #NodeJS in Action#. You can see that the call back function for replace is not consistent. Why?

2
  • I don't see any inconsistency... This works as programmed. What do you expect to happen that isn't happening? Are we meant to guess what "not consistent" means? Commented Oct 10, 2014 at 9:06
  • @spender: They mean that replace callbacks take different parameters. According to MDN the order in the function1 is proper developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Perhaps there's an error in the book or there's some context we're not aware of Commented Oct 10, 2014 at 9:17

1 Answer 1

2

The callback in function2 could be written with a 4th argument to appear less confusing and more consistent with the first callback in your examples:

function function2(format) {
    var regexp = /:(\w+)/g;
    var str = format.replace(regexp,function(match,submatch,position,originalText){
        return match;
    });
    return str;
}

Look at how the callback in replace can be defined: it accepts a number of arguments >= 3. The optional arguments are used only if your regex contains submatches, and they correspond to the nth parenthesized submatch string:

function(match, [p1, p2, ...], offset, string) { ... }

Whats sounds confusing, I guess, is that they are placed in the middle. Also note that the callback function will be invoked multiple times for each full match to be replaced, if the regular expression in the first parameter is global (which is true in your example).

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

Comments

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.