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.
str = pad + str;
), since the data will be reallocated everytime. Append always at end!str += pad;
). It is much faster to append the padding string to itself and extract first x-chars (the parser can do this efficiently if you extract from first char). This is exponential growth, which means that it wastes some memory temporarily (you should not do this with extremely huge texts).Using the ECMAScript 6 method String#repeat, a pad function is as simple as:
String#repeat
is currently supported in Firefox and Chrome only. for other implementation, one might consider the following simple polyfill:Here's a simple function that I use.
For example:
Here is a simple answer in basically one line of code.
Make sure the number of characters in you padding, zeros here, is at least as many as your intended minimum length. So really, to put it into one line, to get a result of "00035" in this case is:
With ES8, there are two options for padding.
You can check them in the documentation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/padStart