【问题标题】:Add multiple consecutive integers in a string在字符串中添加多个连续整数
【发布时间】:2017-02-06 14:30:15
【问题描述】:

我有一些 javascript 代码可以创建一个包含字符和整数的变量。

我需要将此字符串中的连续整数相加,同时不影响其他单个或后续连续整数。

假设我的输入是

GhT111r1y11rt

我需要我的输出是:

GhT3r1y2rt

我该怎么做呢?

【问题讨论】:

    标签: javascript html regex


    【解决方案1】:

    String#replace 方法与回调一起使用,内部回调使用String#splitArray#reduce 方法计算总和。

    console.log(
      'GhT111r1y11rt'.replace(/\d{2,}/g, function(m) { // get all digit combination, contains more than one digit
        return m.split('').reduce(function(sum, v) { // split into individual digit
          return sum + Number(v) // parse and add to sum
        }, 0) // set initial value as 0 (sum)
      })
    )

    \d{2,} 匹配 2 个或更多重复数字,这比 \d+ 更好,因为我们不想替换单个数字。

    【讨论】:

    • @webdeb :这将返回总和(问题:“此字符串中的连续整数要加在一起”
    【解决方案2】:

    isNaN()方法在字符为数字时返回true,使用substr单独检查每个字符

    【讨论】:

      【解决方案3】:

      您可以对重复多次的同一个数字执行此操作(如您的示例字符串):

      'GhT111r1y11rt'.replace(/(\d)\1+/g, function (m,g1) { return g1 * m.length;});
      

      (\d) 捕获第一个数字
      \1+ 重复捕获的数字(来自第 1 组)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-14
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多