Skip to content

Instantly share code, notes, and snippets.

@N8-B
Last active June 18, 2016 17:21
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 N8-B/b9b302448178eeed192c12fe46a0692c to your computer and use it in GitHub Desktop.
Save N8-B/b9b302448178eeed192c12fe46a0692c to your computer and use it in GitHub Desktop.
padLeft - Function for padding strings on the left side
/**
* Pads `string` on the left side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars='0'] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* padLeft('123', 6);
* // => '000123'
*
* padLeft('123', 6, '-');
* // => '---123'
*
* padLeft('123', 3);
* // => '123'
*
* padLeft('1234', 3);
* // => '1234'
*/
function padLeft(string, length, chars) {
string = string == null ? '' : string;
length = length ? length : 0;
chars = chars ? chars : ' ';
var max = (length - string.length)/chars.length,
i;
for (i = 0; i < max; i++) {
string = chars + string;
}
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment