我有一個字符串,看起來像「(3)新東西」,其中3可以是任何數字。
我想添加或減去這個數字。JavaScript:從字符串中的數字加或減
我想通方式如下:
var thenumber = string.match((/\d+/));
thenumber++;
string = string.replace(/\(\d+\)/ ,'('+ thenumber +')');
有沒有更優雅的方式來做到這一點?
我有一個字符串,看起來像「(3)新東西」,其中3可以是任何數字。
我想添加或減去這個數字。JavaScript:從字符串中的數字加或減
我想通方式如下:
var thenumber = string.match((/\d+/));
thenumber++;
string = string.replace(/\(\d+\)/ ,'('+ thenumber +')');
有沒有更優雅的方式來做到這一點?
我相信濃湯是在正確的軌道
"(42) plus (1)".replace(/\((\d+)\)/g, function(a,n){ return "("+ (+n+1) +")"; });
擴展字符串對象的缺點,它看起來不錯。然後
String.prototype.incrementNumber = function() {
var thenumber = string.match((/\d+/));
thenumber++;
return this.replace(/\(\d+\)/ ,'('+ thenumber +')');
}
用法是:
alert("(2) New Stuff".incrementNumber());
我相信你的方法,你可以有以下原因最好優雅:
短包裝成一個函數這一點,我不認爲有很多內容做
另一種方式:
string = string.replace(/\((\d+)\)/ , function($0, $1) { return "(" + (parseInt($1, 10) + 1) + ")"; });
由於加萊說,我不認爲你的解決方案是一個壞的,但這裏是將在一個指定的位置指定的值添加到一個數的函數一個字符串。
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));
不像陣列,我不認爲在延長字符串是不好的。既然你迭代了多少次String對象? – 2009-02-02 18:21:43