Posted By

MMDeveloper on 09/16/08


Tagged

javascript String Pad Left


Versions (?)

Left Pad String


 / Published in: JavaScript
 

URL: http://www.mechanicmatt.com

  1. function leadingZeros(num, totalChars, padWith) {
  2. num = num + "";
  3. padWith = (padWith) ? padWith : "0";
  4. if (num.length < totalChars) {
  5. while (num.length < totalChars) {
  6. num = padWith + num;
  7. }
  8. } else {}
  9.  
  10. if (num.length > totalChars) { //if padWith was a multiple character string and num was overpadded
  11. num = num.substring((num.length - totalChars), totalChars);
  12. } else {}
  13.  
  14. return num;
  15. }
  16.  
  17. alert(leadingZeros("asdf", 10, "0"));

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: aaajs on November 13, 2008

String.prototype.leftPad = function (l, c) { return new Array(l - this.length + 1).join(c || '0') + this; }

You need to login to post a comment.