Skip to content

Instantly share code, notes, and snippets.

@wafflesnatcha
Last active June 10, 2024 12:49
Show Gist options
  • Save wafflesnatcha/3694295 to your computer and use it in GitHub Desktop.
Save wafflesnatcha/3694295 to your computer and use it in GitHub Desktop.
JavaScript: String.leftPad()
/**
* 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;
};
}
@ioslh
Copy link

ioslh commented Mar 23, 2016

str = str+"" || " "

This is better when str is a int 0

@Lokno
Copy link

Lokno commented Mar 23, 2016

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);

@mrcraftar
Copy link

ATERNOS USE THIS:0

@Nikilites
Copy link

FR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment