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; | |
}; | |
} |
ATERNOS USE THIS:0
FR
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The call to substr() is vestigial since you are already defining the length of the pad with the size of the array object. Also, since you're creating an array, you could simply push the original str to the end of it before the join(), making sure to remove the ' + 1' from the initial size.
a = new Array((((length - this.length) / str.length) | 0));
a.push(this);
return a.join(str);