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:
String.prototype.pad = function(l, s, t){
return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
+ 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
+ this + s.substr(0, l - t) : this;
};
Example:
<script type="text/javascript">
//<![CDATA[
var s = "Jonas";
document.write(
'<h2>S = '.bold(), s, "</h2>",
'S.pad(20, "[]", 0) = '.bold(), s.pad(20, "[]", 0), "<br />",
'S.pad(20, "[====]", 1) = '.bold(), s.pad(20, "[====]", 1), "<br />",
'S.pad(20, "~", 2) = '.bold(), s.pad(20, "~", 2)
);
//]]>
</script>
But I have no idea what the heck it is doing and it doesn't seem to work for me.
The key trick in both those solutions is to create an
array
instance with a given size (one more than the desired length), and then to immediately call thejoin()
method to make astring
. Thejoin()
method is passed the paddingstring
(spaces probably). Since thearray
is empty, the empty cells will be rendered as emptystrings
during the process of joining thearray
into one resultstring
, and only the padding will remain. It's a really nice technique.A faster method
If you are doing this repeatedly, for example to pad values in an array, and performance is a factor, the following approach can give you nearly a 100x advantage in speed (jsPerf) over other solution that are currently discussed on the inter webs. The basic idea is that you are providing the pad function with a fully padded empty string to use as a buffer. The pad function just appends to string to be added to this pre-padded string (one string concat) and then slices or trims the result to the desired length.
For example, to zero pad a number to a length of 10 digits,
To pad a string with whitespace, so the entire string is 255 characters,
Performance Test
See the jsPerf test here.
And this is faster than ES6
string.repeat
by 2x as well, as shown by the revised JsPerf hereECMAScript 2017 adds a padStart method to the String prototype. This method will pad a string with spaces to a given length. This method also takes an optional string that will be used instead of spaces for padding.
A padEnd method was also added that works in the same manner.
For browser compatibility (and a useful polyfill) see this link.
padding string has been inplemented in new javascript version.
str.padStart(targetLength [, padString])
https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/padStart
If you want your own function check this example:
A variant of @Daniel LaFavers' answer.
For example:
If you don't mind including a utility library, lodash library has _.pad, _.padLeft and _.padRight functions.