Skip to content

Instantly share code, notes, and snippets.

@tbusser
Created March 6, 2015 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbusser/148d87c0430e96bbb66c to your computer and use it in GitHub Desktop.
Save tbusser/148d87c0430e96bbb66c to your computer and use it in GitHub Desktop.
Pad string
/**
* Pads a string so it will reach the requested number of characters. The
* padding will be added to the left of the original string.
*
* @param {string} value The original string, unpadded.
* @param {Number} length The desired length for the value string. Please
* note that this value should be equal to or exceed
* the unpadded length of the value parameter or
* else the result will be a clipped string.
* @param {string} padChar The character to use to pad the string. When no
* char is provided it will use 0 as the padding
* character.
*
* @return {string} The result is the original string padded on the
* left with as many times the padded char to have
* the resulting string reach the requested width.
*/
function padString(value, length, padChar) {
if (padChar == null || padChar === '') {
padChar = '0';
}
// To create a string with the specified padChar repeated as many times
// as the requested length we will create an Array with the requested
// string length plus 1 extra. We need to extra element because in order
// to create the string we will join these empty array items together
// using the padding char as the separator. If the requested length is
// 2 and we would join these together the separator would appear only
// once, this is why we need to extra empty array item.
// When we have a string with the desired length and filled with the
// padding char we will append the value to the string. Now we take the
// number of requested chars, starting at the back of the string using
// substr with a negative number. This way we are sure it will include
// the value passed along as well as the necessary number of padding
// characters to reach the desired string length
return (new Array(length + 1).join(padChar) + value).substr(-length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment