传递函数替换时如何获得匹配的组?

时间:2011-09-18 10:28:33

标签: javascript regex replace

我有以下代码:

this.parse = function(whatToParse, currentItem) {
    var re = /\{j\s([a-z0-9\.\|_]+)\ss\}/gi;
    var newResult = whatToParse.replace(re, function(matches){
        alert(matches);
    });
}

whatToParse是:

            <h1>
                {j name s}
            </h1>
            <div>
                <nobr>{j description s}</nobr>
            </div>

但为什么匹配不是数组呢?它仅包含匹配的字符串,不包含组。 例如:alert(matches);提醒“{j name s}”和alert(matches[1]);提醒“j”。

为什么呢?如何获得第一组?

P.S。我不明白,因为在PHP中这个RegExp工作正常。

1 个答案:

答案 0 :(得分:1)

请参阅documentation [MDN]。捕获的值作为参数传递给函数。

  

该函数的参数如下:

Possible name   Supplied value
str             The matched substring. (Corresponds to $& above.)
p1, p2, ...     The nth parenthesized submatch string, provided the first argument to replace was a RegExp object. (Correspond to $1, $2, etc. above.)
offset          The offset of the matched substring within the total string being examined. (For example, if the total string was "abcd", and the matched substring was "bc", then this argument will be 1.)
s               The total string being examined.

(抱歉格式化,但在Markdown中创建表格并不容易)

所以在你的情况下:

var newResult = whatToParse.replace(re, function(match, firstGroup){
    alert(firstGroup);
});