Pad A String In JavaScript

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.

function pad(padMe, totalChars, padWith) {
  padMe = padMe + ""; // force num to be string
 padWith = (padWith) ? padWith :"0"; // set default pad
 if ( padMe.length < totalChars ) {
  while ( padMe.length < totalChars ) {
    padMe = padWith + padMe;
  }
 }
 return padMe;
}

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.

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

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.