Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.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中的出现次数?_Javascript_Php_Regex - Fatal编程技术网

如何定义JavaScript中的出现次数?

如何定义JavaScript中的出现次数?,javascript,php,regex,Javascript,Php,Regex,在PHP中,第四个参数将出现次数限制为该数字: mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) 例如: $string = 'this is a test'; $pattern = '/s/'; echo preg_replace($pattern, 'S', $string, 1); //=> thiS

在PHP中,第四个参数将出现次数限制为该数字:

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
例如:

$string = 'this is a test';
$pattern = '/s/';
echo preg_replace($pattern, 'S', $string, 1);
//=> thiS is a test

/* If I remove that 1 which is the last argument in preg_replace, the output will be:
*  "thiS iS a teSt"
*/

如何在JavaScript中执行此操作?

您可以在replace方法之外启动一个计数器(就像我在下面的函数中所做的那样):

函数替换($pattern,$replacement,$subject,$limit){
var计数器=0;
返回$subject.replace($模式,函数(匹配){
return++计数器>$limit?匹配:$replacement;
});
}
var$string='这是一个测试';
var$pattern=/s/g;
O.innerHTML=replace($pattern,'S',$string,1)+'\n
+替换($pattern,$S',$string,2)
试试这个:

var string = "this is test"
   ,pattern = /s/g
   ,replacement = "S"
   ,maxReplacements = 2
   ,i = 0

console.log(string.replace(pattern, match=> i++ >= maxReplacements ? match : replacement))
它只计算替换数,如果超过2,则停止替换


请参阅上的演示。

这是JS中的默认行为。如果你想交换所有的东西,你必须添加全局标志-
/s/g
@ClasG是的,我熟悉JS中的
g
标志,但我想知道如何限制交换的具体数字?例如,在JS中,您可以使用不带
g
标志的正则表达式替换某个对象一次:
“这是一个测试”。替换(/s/,“s”)
。如果使用
g
标志,它将替换所有出现的情况。我不知道有什么简单的方法可以替换多达n次。据我所知,JS不支持这一点。也许其他人知道。如果没有一个简单的
for
-循环,我可能会添加。只有一个问题,
x
在这行
return++counter>limit中是什么?x:‘S’?您尚未定义它,因此它包含什么?
x
作为arg(macthed text)@stack。我将其更改为
match