0

我有一个使用占位符的字符串,我试图用函数的结果替换它。给出一个想法:

sometext = "%number% text text %number%"replace(/%\w+%/g, function(parm) {
       return 'customtext';
}

我想知道有没有办法获得比赛的数量?我需要那个数字,所以我可以检查当前正在运行的函数是否替换了最后一个元素,如果是,则返回其他内容。函数体中的类似内容

if(lastElement) {
   return 'something else';
}

sometext = "%number% text text %number%"replace(/%\w+%/g, function(parm) {
       return 'customtext';
4

4 回答 4

1

您无法直接获取函数中的匹配数。它没有提供。

我只是简单地计算它,然后计算替换期间的函数调用:

var i = 0, n = str.split(/%\w+%/).length-1;
var sometext = str.replace(/%\w+%/g, function() {
   if (++i==n) return 'last text';
   else return 'not last text';
});
于 2013-04-06T17:57:59.167 回答
0

我想你想使用 javascript 的 .match() 函数。你给它一个正则表达式,它会返回一个匹配数组。然后,您可以获得数组的长度。

看:

http://www.w3schools.com/jsref/jsref_match.asp

于 2013-04-06T17:54:55.907 回答
0

这将给出匹配的数量:

var last = "%number% text text %number%".match(/%\w+%/g).length;

然后把你的'if'放在你正在使用的回调中,并跟踪一个计数器,与上面收集的长度相比,回调执行了多少次,瞧。

干杯。

于 2013-04-06T17:56:22.227 回答
0

首先,找到匹配的数量:

var matchCount = haystack.match(needle);

然后,倒计时每次替换的剩余匹配数:

haystack.replace(needle, function(param) {
    matchCount--;
    if( matchCount == 0 ) {
        return 'Last Element';
    }
    return 'Not Last Element';
});

合并后的代码如下所示:

var haystack = "%number% text text %number%";
var needle = new RegExp("%\w+%", "g");

var matchCount = haystack.match(needle);
haystack.replace(needle, function(param) {
    matchCount--;
    if( matchCount == 0 ) {
        return 'Last Element';
    }
    return 'Not Last Element';
});

并且可以缩短为类似这样的函数:

function customReplace(haystack, needle) {
    var count = haystack.match(needle);
    haystack.replace(needle, function() {
        return (--count ? 'notLast' : 'isLast');
    });
}
于 2013-04-06T18:20:57.690 回答