Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript str.replace()、获取匹配数或替换的最后一个元素?_Javascript - Fatal编程技术网

Javascript str.replace()、获取匹配数或替换的最后一个元素?

Javascript str.replace()、获取匹配数或替换的最后一个元素?,javascript,Javascript,我有一个字符串,它使用占位符,我正试图用函数的结果替换占位符。请给出一个想法: sometext = "%number% text text %number%"replace(/%\w+%/g, function(parm) { return 'customtext'; } 我想知道的是有没有一种方法可以得到匹配的数量?我需要这个数字,这样我就可以检查当前运行的函数是否正在替换最后一个元素,如果是,则返回其他内容。类似于函数体中的内容 if(lastElement) { r

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

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';

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

见:


这将给出匹配数:

var last = "%number% text text %number%".match(/%\w+%/g).length;
var matchCount = haystack.match(needle);
然后将您的“if”放在您正在使用的回调中,并使用计数器跟踪回调执行的次数,与上面收集的长度进行比较


干杯。

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

我只需在替换之前计算它,并在替换过程中计算函数调用:

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';
});

首先,查找匹配数:

var last = "%number% text text %number%".match(/%\w+%/g).length;
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');
    });
}

MDN是一个比W3Schools好得多的来源—MDN更准确、更详细。