最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - question about javascript string's replace method - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Mar 1, 2010 at 2:47 Just a learnerJust a learner 28.7k53 gold badges165 silver badges247 bronze badges 1
  • 3 ...whoa, you can use a callback? Neat! – Matchu Commented Mar 1, 2010 at 2:52
Add a ment  | 

2 Answers 2

Reset to default 10

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
});
var str = 'abc';
str = str.replace('b', function (match) {
    // (!) List of actual arguments depends from template of RegEx >>>
    var offset = arguments.length - 1, full = arguments[offset];
    offset = arguments[offset - 1];
    // (!) But the first argument is match
    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
});
发布评论

评论列表(0)

  1. 暂无评论