开发者

Javascript: Add +1 to number that starts with 0 (like 01, 02, 03) and keep the zero

I like to add (+1) to a number. But problem is my number can sometimes have 0 preceding it. Like 01, 02, 03, 04. So I like result to be:

mockup开发者_JAVA技巧01 + 1 = mockup02
mockup11 + 1 = mockup12

How can that be achieved? Example of how I would use it would be if I had filename named mockup_01.htm and change it to mockup_02.htm

Thanks!


Maybe this

 next = (parseInt(number, 10) + 101).toString().substr(1)

to make a mockup_02.htm out of mockup_01 try this

newName = fileName.replace(/\d+(?=\.)/, function(n) {
    return (parseInt(n, 10) + Math.pow(10, n.length) + 1).toString().substr(1)
});

this works with numbers of any length, e.g. mockup_0001, mockup_000001 etc


I'm not a javascript programmer, but it seems like you're mixing up presentation and internal representation. If the "01" is a string, with a corresponding integer variable, you can convert from the string to the integer, add 1, and then make a new string with the desired formatting. This is sometimes referred to as a model-view-controller pattern. The model is the integer variable - it models the internal behavior of numbers. The view is the string - it presents the number in a human readable fashion. The controller handles the numerical operations.


function next_id(input) {
  var output = parseInt(input, 10)+1; // parse and increment
  output += ""; // convert to string
  while (output.length<2) output = "0"+output; // prepend leading zeros
  return output;
}

var id = "00";
for (var i=0; i<20; i++) {
  console.log(id);
  id = next_id(id);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜