Chill Web Designs Chill Web Designs - 7 months ago 28
Javascript Question

Adding extra zeros in front of a number using jQuery?

I have file that are uploaded which are formatted like so


MR 1

MR 2

MR 100

MR 200

MR 300

ETC.


What i need to do is add extra two 00s before anything before MR 10 and add one extra 0 before MR10-99

So files are formatted


MR 001

MR 010

MR 076

ETC.


Any help would be great!

Answer

Assuming you have those values stored in some strings, try this:

function pad (str, max) {
  str = str.toString();
  return str.length < max ? pad("0" + str, max) : str;
}

pad("3", 3);    // => "003"
pad("123", 3);  // => "123"
pad("1234", 3); // => "1234"

var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"