在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方法之外启动计数器(就像我在下面的函数中所做的那样):
function replace($pattern, $replacement, $subject, $limit) {
var counter = 0;
return $subject.replace($pattern, function(match) {
return ++counter > $limit ? match : $replacement;
});
}
var $string = 'this is a test';
var $pattern = /s/g;
O.innerHTML = replace($pattern, 'S', $string, 1) + ''n'
+ replace($pattern, 'S', $string, 2);
<pre id=O>
希望有帮助:)
试试这个:
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 Bin上的演示。