Last active
June 10, 2024 12:49
-
-
Save wafflesnatcha/3694295 to your computer and use it in GitHub Desktop.
JavaScript: String.leftPad()
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
/** | |
* Pad a string to a certain length with another string. | |
* | |
* @param {Number} size The resulting padded string length. | |
* @param {String} [str=" "] String to use as padding. | |
* @returns {String} The padded string. | |
*/ | |
if (!String.prototype.leftPad) { | |
String.prototype.leftPad = function (length, str) { | |
if (this.length >= length) { | |
return this; | |
} | |
str = str || ' '; | |
return (new Array(Math.ceil((length - this.length) / str.length) + 1).join(str)).substr(0, (length - this.length)) + this; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FR