Pad A String In JavaScript

24th September 2008 - 2 minutes read time

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. padMe = padMe + ""; // force num to be string
  3. padWith = (padWith) ? padWith :"0"; // set default pad
  4. if ( padMe.length < totalChars ) {
  5. while ( padMe.length < totalChars ) {
  6. padMe = padWith + padMe;
  7. }
  8. }
  9. return padMe;
  10. }

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.

  1. alert(pad("1", 4, "0")); // 0001
  2. alert(pad("9", 4, "7")); // 7779
  3. alert(pad("0002", 7, "this is a string")); // this is a string 0002
  4. alert(pad("12345", 4, "0")); // 12345

Ā 

Add new comment

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