LOKESH
LOKESH

Reputation: 1301

How to pad leading zero in javascript

I have java script that that add 1 to last 4 digit of var c.

If 0001 then it show 0002. But if result exceeding 9999 then it show 0000. And I need answer 10000, so which function I have to use in javascript? Instead of (pad+str).slice(-pad.lenght)

My main function is here

function autonum(){                           
    var c = 'BLHC-2014-0001';

    var d = c.split("-");
    var e = d[2];
    var f = parseInt(e,10);
    var g = f+1;        
    var str = '' + g;
    var pad = "0000";    
    var resu = (pad+str).slice(-pad.length);
    var lt = d[0]+'-'+d[1]+'-'+resu;               
    document.getElementById("pnum").value =lt;
}

Upvotes: 2

Views: 193

Answers (2)

JLRishe
JLRishe

Reputation: 101768

You can do this:

var resu = pad.slice(str.length) + str;

http://jsfiddle.net/s23v3/

Upvotes: 4

Bergi
Bergi

Reputation: 665555

You could make a simple conditional:

var resu = str.length < 4 ? (pad+str).slice(-4) : str;

Upvotes: 3

Related Questions