Last active
June 18, 2016 17:21
-
-
Save N8-B/b9b302448178eeed192c12fe46a0692c to your computer and use it in GitHub Desktop.
padLeft - Function for padding strings on the left side
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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