vote up 2 vote down star

Hi guys,

I know that I can pass a string as the second parameter to the JavaScript string object's replace method. In this case I can use $` and $' to reference the left/right part text of a successful match. Now my question is, If I pass a callback function as the second parameter, how can I get the same information? I want to use this infomation in the callback function. Great thanks.

flag

2  
...whoa, you can use a callback? Neat! – Matchu Mar 1 at 2:52

1 Answer

vote up 3 vote down check

See Mozilla's documentation; you won't get that data for free.

The good news is, you will get the offset of the match as your second-to-last argument, and the total string as the last. So you can run your own substring functions.

var str = 'abc';
str = str.replace('b', function (match, offset, full) {
    var before = full.substr(0, offset),
        after = full.substr(offset + 1, full.length - offset);
    return 'foo'; // or, ya know, something actually using before and after
});
link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.