views:

412

answers:

3

Hi, 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!

+1  A: 

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.

mtrw
No offense, but MVC isn't for everything. I think you are over-architecting the problem.
chakrit
@chakrit - You're right. I mean MVC just as a model for thinking, not actually connecting up the handlers and callback for every little variable. But stereofrog's (very good) answer handles the representation->data->representation changes in one line. It's important to realize all those changes are necessary to solve the problem, right?
mtrw
+6  A: 

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

stereofrog
+1 for remembering the , 10. Otherwise, it will parse numbers starting with 0 as octals ("031" would become 25).
Joey Adams
brilliant! thanks!
Scott
Wondering if you know how it would work if I wanted to include the entire string... likemockup_01.htm to mockup02.htm
Scott
see update.........
stereofrog
hey thanks a lot!! tried to give you another (+) for answer but think it didnt work.
Scott
+2  A: 
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);
}
Darwin
+1 - Could make it a little more reusable by getting the `var desiredLength=(''+input).length` then doing `while (output.length<desiredLength)` So it would work with `01` or `007` ;)
gnarf