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:
It's 2014, and I suggest a Javascript string-padding function. Ha!
Bare-bones: right-pad with spaces
function pad ( str, length ) {
var padding = ( new Array( Math.max( length - str.length + 1, 0 ) ) ).join( " " );
return str + padding;
}
Fancy: pad with options
/**
* @param {*} str input string, or any other type (will be converted to string)
* @param {number} length desired length to pad the string to
* @param {Object} [opts]
* @param {string} [opts.padWith=" "] char to use for padding
* @param {boolean} [opts.padLeft=false] whether to pad on the left
* @param {boolean} [opts.collapseEmpty=false] whether to return an empty string if the input was empty
* @returns {string}
*/
function pad ( str, length, opts ) {
var padding = ( new Array( Math.max( length - ( str + "" ).length + 1, 0 ) ) ).join( opts && opts.padWith || " " ),
collapse = opts && opts.collapseEmpty && !( str + "" ).length;
return collapse ? "" : opts && opts.padLeft ? padding + str : str + padding;
}
Usage (fancy):
pad( "123", 5 );
// returns "123 "
pad( 123, 5 );
// returns "123 " - non-string input
pad( "123", 5, { padWith: "0", padLeft: true } );
// returns "00123"
pad( "", 5 );
// returns " "
pad( "", 5, { collapseEmpty: true } );
// returns ""
pad( "1234567", 5 );
// returns "1234567"