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.