【问题标题】:How can I define the number of occurrence in JavaScript?如何定义 JavaScript 中的出现次数?
【发布时间】: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


【解决方案1】:

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

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>

希望对你有帮助:)

【讨论】:

  • 只有一个问题,return ++counter > limit ? x : 'S'; 这一行中的x 是什么?你还没有定义它,那么它包含什么?
  • x 被视为 arg(加工文本)
  • @stack。我把它改成了match
【解决方案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 Bin 上查看演示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    相关资源
    最近更新 更多