 <p>Here's a simple function that I use.</p> <pre><code>var pad=function(num,field){ var n = '' + num; var w = n.length; var l = field.length; var pad = w &lt; l ? l-w : 0; return field.substr(0,pad) + n; }; </code></pre> <p>For example:</p> <pre><code>pad (20,' '); // 20 pad (321,' '); // 321 pad (12345,' '); //12345 pad ( 15,'00000'); //00015 pad ( 999,'*****'); //**999 pad ('cat','_____'); //__cat </code></pre>