Pad A String In JavaScript

24th September 2008

Use the following function to pad a string with to a set length with a given string. The function takes three parameters. The string to be padded, the total number of characters that the string must be, and the string to be added. If the third parameter is not given then 0 is used as a default.

  1. function pad(padMe, totalChars, padWith)
  2. {
  3. padMe = padMe + ""; // force num to be string
  4. padWith = (padWith) ? padWith :"0"; // set default pad
  5. if ( padMe.length
  6.  
  7. Here are some examples of the function in action. If the string given is longer than the required pad length then the string is returned unchanged.
  8.  
  9. alert(pad("1", 4, "0")); // 0001
  10. alert(pad("9", 4, "7")); // 7779
  11. alert(pad("0002", 7, "this is a string")); // this is a string 0002
  12. alert(pad("12345", 4, "0")); // 12345

Add new comment

The content of this field is kept private and will not be shown publicly.