在 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>
希望对您有所帮助:)
关于javascript - 如何定义 JavaScript 中的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36519221/