最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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:

mockup01 + 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!

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:

mockup01 + 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!

Share Improve this question edited Mar 22, 2010 at 21:38 Scott Yu - builds stuff asked Mar 22, 2010 at 21:21 Scott Yu - builds stuffScott Yu - builds stuff 11.8k8 gold badges43 silver badges55 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 14

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)

  1. 暂无评论