【发布时间】:2016-04-09 16:00:45
【问题描述】:
在 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 中做到这一点?
【问题讨论】:
-
这是 JS 中的默认行为。如果你想交换所有你必须添加 global 标志 -
/s/g -
@ClasG 是的,我对JS中的
g标志很熟悉,但是我想知道如何限制交换具体数量?例如只有 3 次首次出现。 -
在 JS 中,您可以使用不带
g标志的正则表达式来替换一次:"this is a test".replace(/s/, "S")。如果您使用g标志,它将替换所有出现的位置。我不知道有什么简单的方法可以替换多达 n 次。 -
据我所知 JS 不支持。也许其他人知道。
-
如果没有简单的
for-loop 我可能会添加。
标签: javascript php regex