Comme dit GALETS, je ne pense pas que votre solution est mauvaise, mais ici est une fonction qui ajoutera une valeur spécifiée à un numéro dans une position spécifiée dans un string.
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));
Contrairement Array, je ne pense pas la chaîne d'extension est mauvais. Depuis combien de fois itérez-vous les objets String? –
J'aime cette approche aussi, moi-même. –