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:
A little late, but thought I might share anyway. I found it useful to add a prototype extension to Object. That way I can pad numbers and strings, left or right. I have a module with similar utilities I include in my scripts.
// include the module in your script, there is no need to export
var jsAddOns = require('/jsAddOns');
~~~~~~~~~~~~ jsAddOns.js ~~~~~~~~~~~~
/*
* method prototype for any Object to pad it's toString()
* representation with additional characters to the specified length
*
* @param padToLength required int
* entire length of padded string (original + padding)
* @param padChar optional char
* character to use for padding, default is white space
* @param padLeft optional boolean
* if true padding added to left
* if omitted or false, padding added to right
*
* @return padded string or
* original string if length is >= padToLength
*/
Object.prototype.pad = function(padToLength, padChar, padLeft) {
// get the string value
s = this.toString()
// default padToLength to 0
// if omitted, original string is returned
padToLength = padToLength || 0;
// default padChar to empty space
padChar = padChar || ' ';
// ignore padding if string too long
if (s.length >= padToLength) {
return s;
}
// create the pad of appropriate length
var pad = Array(padToLength - s.length).join(padChar);
// add pad to right or left side
if (padLeft) {
return pad + s;
} else {
return s + pad;
}
};