【问题标题】:JavaScript: add or subtract from number in stringJavaScript:对字符串中的数字进行加法或减法
【发布时间】:2009-02-02 18:14:33
【问题描述】:

我有一个看起来像“(3) New stuff”的字符串,其中 3 可以是任意数字。
我想增加或减少这个数字。

我想出了以下方法:

var thenumber = string.match((/\d+/));
thenumber++;
string = string.replace(/\(\d+\)/ ,'('+ thenumber +')');

有更优雅的方法吗?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    另一种方式:

    string = string.replace(/\((\d+)\)/ , function($0, $1) { return "(" + (parseInt($1, 10) + 1) + ")"; });
    

    【讨论】:

      【解决方案2】:

      我相信 Gumbo 是在正确的轨道上

      "(42) plus (1)".replace(/\((\d+)\)/g, function(a,n){ return "("+ (+n+1) +")"; });
      

      【讨论】:

        【解决方案3】:

        没有扩展 String 对象,我觉得很好。

        String.prototype.incrementNumber = function () {
          var thenumber = string.match((/\d+/));
          thenumber++;
          return this.replace(/\(\d+\)/ ,'('+ thenumber +')');
        }
        

        然后用法是:

        alert("(2) New Stuff".incrementNumber());
        

        【讨论】:

        • 与数组不同,我认为扩展字符串并没有那么糟糕。因为你迭代了多少次 String 对象?
        • 我自己也喜欢这种方法。
        【解决方案4】:

        我相信你的方法是最优雅的,原因如下:

        • 由于输入不是一个“干净”的数字,您确实需要使用某种字符串解析器。使用正则表达式是代码效率非常高的方法
        • 通过查看代码,很清楚它的作用

        没有把它包装成一个函数,我认为没有更多工作要做

        【讨论】:

          【解决方案5】:

          正如 galets 所说,我认为您的解决方案不是一个坏的解决方案,但这里有一个函数,可以将指定值添加到字符串中指定位置的数字。

          var str = "fluff (3) stringy 9 and 14 other things";
          
          function stringIncrement( str, inc, start ) {
              start = start || 0;
              var count = 0;
              return str.replace( /(\d+)/g, function() {
                  if( count++ == start ) {
                      return(
                          arguments[0]
                          .substr( RegExp.lastIndex )
                          .replace( /\d+/, parseInt(arguments[1])+inc )
                      );
                  } else {
                      return arguments[0];
                  }
              })
          }
          
          // fluff (6) stringy 9 and 14 other things :: 3 is added to the first number
          alert( stringIncrement(str, 3, 0) );
          
          // fluff (3) stringy 6 and 14 other things :: -3 is added to the second number
          alert( stringIncrement(str, -3, 1) );
          
          // fluff (3) stringy 9 and 24 other things :: 10 is added to the third number
          alert( stringIncrement(str, 10, 2) );
          

          【讨论】:

            猜你喜欢
            • 2010-09-12
            • 2012-12-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-03-26
            • 1970-01-01
            相关资源
            最近更新 更多