I am in need of a JavaScript function which can take a value and pad it to a given length (I need spaces, but anything would do). I found this:
Code:
es7 is just drafts and proposals right now, but if you wanted to track compatibility with the spec, your pad functions need:
From my polyfill library, but apply your own due diligence for prototype extensions.
// Tests
'hello'.lpad(4) === 'hello'
'hello'.rpad(4) === 'hello'
'hello'.lpad(10) === ' hello'
'hello'.rpad(10) === 'hello '
'hello'.lpad(10, '1234') === '41234hello'
'hello'.rpad(10, '1234') === 'hello12341'
String.prototype.lpad || (String.prototype.lpad = function( length, pad )
{
if( length < this.length ) return this;
pad = pad || ' ';
let str = this;
while( str.length < length )
{
str = pad + str;
}
return str.substr( -length );
});
String.prototype.rpad || (String.prototype.rpad = function( length, pad )
{
if( length < this.length ) return this;
pad = pad || ' ';
let str = this;
while( str.length < length )
{
str += pad;
}
return str.substr( 0, length );
});