Simplest inline method to left pad a string

JavascriptString

Javascript Problem Overview


> Possible Duplicate:
> Is there a JavaScript function that can pad a string to get to a determined length?

What's the simplest way to left pad a string in javascript?

I'm looking for an inline expression equivalent to mystr.lpad("0", 4): for mystr='45' would return 0045.

Javascript Solutions


Solution 1 - Javascript

Found a simple one line solution:

("0000" + n).slice(-4)

If the string and padding are in variables, you would have:

mystr = '45'
pad = '0000'
(pad + mystr).slice(-pad.length)

Answer found here, thanks to @dani-p. Credits to @profitehlolz.

Solution 2 - Javascript

function pad(value, length) {
    return (value.toString().length < length) ? pad("0"+value, length):value;
}

Solution 3 - Javascript

Something like below:

String.prototype.lpad = function(padString, length) {
	var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}
console.log('45'.lpad('0', 4)); // "0045"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel ReisView Question on Stackoverflow
Solution 1 - JavascriptDaniel ReisView Answer on Stackoverflow
Solution 2 - JavascriptKevin BowersoxView Answer on Stackoverflow
Solution 3 - JavascriptxdazzView Answer on Stackoverflow