繁体   English   中英

JavaScript:对字符串中的数字进行加减

[英]JavaScript: add or subtract from number in string

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

我想出了以下方法:

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

有更优雅的方法吗?

其他方式:

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

我相信Gumbo的发展方向正确

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

没有扩展String对象,对我来说看起来不错。

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

用法如下:

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

我相信您的方法是您可以拥有的最好的方法,原因如下:

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

没有将其包装到函数中,我不认为还有更多要做的事情

正如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) );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM