[javascript] 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!

This question is related to javascript

The answer is


If you split on the space, you can add leading zeros using a simple function like:

function addZeros(n) {
  return (n < 10)? '00' + n : (n < 100)? '0' + n : '' + n;
}

So you can test the length of the string and if it's less than 6, split on the space, add zeros to the number, then join it back together.

Or as a regular expression:

function addZeros(s) {
  return s.replace(/ (\d$)/,' 00$1').replace(/ (\d\d)$/,' 0$1');
}

I'm sure someone can do it with one replace, not two.

Edit - examples

alert(addZeros('MR 3'));    // MR 003
alert(addZeros('MR 23'));   // MR 023
alert(addZeros('MR 123'));  // MR 123
alert(addZeros('foo bar 23'));  // foo bar 023

It will put one or two zeros infront of a number at the end of a string with a space in front of it. It doesn't care what bit before the space is.


Just for a laugh do it the long nasty way....:
(NOTE: ive not used this, and i would not advise using this.!)

function pad(str, new_length) {
    ('00000000000000000000000000000000000000000000000000' + str).
    substr((50 + str.toString().length) - new_length, new_length)
}

This is the function that I generally use in my code to prepend zeros to a number or string.

The inputs are the string or number (str), and the desired length of the output (len).

var PrependZeros = function (str, len) {
    if(typeof str === 'number' || Number(str)){
    str = str.toString();
    return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
    for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
    return str;
}

};

Examples:

PrependZeros('MR 3',3);    // MR 003
PrependZeros('MR 23',3);   // MR 023
PrependZeros('MR 123',3);  // MR 123
PrependZeros('foo bar 23',3);  // foo bar 023

In simple terms we can written as follows,

for(var i=1;i<=31;i++)
    i=(i<10) ? '0'+i : i;

//Because most of the time we need this for day, month or amount matters.


By adding 100 to the number, then run a substring function from index 1 to the last position in right.

var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);

console.log(month,day);

you will got this result from the date of 2020-11-3

11,03

I hope the answer is useful


var str = "43215"; 
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
                                str = "0" + str;

                        }
console.log("After : \n string :"+str+"\n Length :"+str.length);

It worked for me ! To increase the zeroes, update the 'max' variable

Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:


Note: see Update 2 if you are using latest ECMAScript...


Here a solution I liked for its simplicity from an answer to a similar question:

var n = 123

String('00000' + n).slice(-5); // returns 00123
('00000' + n).slice(-5);       // returns 00123

UPDATE

As @RWC suggested you can wrap this of course nicely in a generic function like this:

function leftPad(value, length) { 
    return ('0'.repeat(length) + value).slice(-length); 
}

leftPad(123, 5); // returns 00123

And for those who don't like the slice:

function leftPad(value, length) {
    value = String(value);
    length = length - value.length;
    return ('0'.repeat(length) + value)
}

But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.

UPDATE 2

In ES6 the String class now comes with a inbuilt padStart method which adds leading characters to a string. Check MDN here for reference on String.prototype.padStart(). And there is also a padEnd method for ending characters.

So with ES6 it became as simple as:

var n = 123;
n.padStart(5, '0'); // returns 00123

function addLeadingZeros (n, length)
{
    var str = (n > 0 ? n : -n) + "";
    var zeros = "";
    for (var i = length - str.length; i > 0; i--)
        zeros += "0";
    zeros += str;
    return n >= 0 ? zeros : "-" + zeros;
}

//addLeadingZeros (1, 3) =   "001"
//addLeadingZeros (12, 3) =  "012"
//addLeadingZeros (123, 3) = "123"

I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:

function lpad(n, e, d) {
  var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
  if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
  return o; }

Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.


str could be a number or a string.

formatting("hi",3);
function formatting(str,len)
{
   return ("000000"+str).slice(-len);
}

Add more zeros if needs large digits


I have a potential solution which I guess is relevent, I posted about it here:

https://www.facebook.com/antimatterstudios/posts/10150752380719364

basically, you want a minimum length of 2 or 3, you can adjust how many 0's you put in this piece of code

var d = new Date();
var h = ("0"+d.getHours()).slice(-2);
var m = ("0"+d.getMinutes()).slice(-2);
var s = ("0"+d.getSeconds()).slice(-2);

I knew I would always get a single integer as a minimum (cause hour 1, hour 2) etc, but if you can't be sure of getting anything but an empty string, you can just do "000"+d.getHours() to make sure you get the minimum.

then you want 3 numbers? just use -3 instead of -2 in my code, I'm just writing this because I wanted to construct a 24 hour clock in a super easy fashion.


Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.

var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);

Know this is an old post, but here's another short, effective way: zeros

edit: dur. if num isn't string, you'd add:

len -= String(num).length;

else, it's all good

function addLeadingZeros(sNum, len) {
    len -= sNum.length;
    while (len--) sNum = '0' + sNum;
    return sNum;
}