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.
A friend asked about using a JavaScript function to pad left. It turned into a little bit of an endeavor between some of us in chat to code golf it. This was the result:
It ensures that the value to be padded is a string, and then if it isn't the length of the total desired length it will pad it once and then recurse. Here is what it looks like with more logical naming and structure
The example we were using was to ensure that numbers were padded with
0
to the left to make a max length of 6. Here is an example set:Using the ECMAScript 6 method String#repeat and Arrow functions, a pad function is as simple as:
jsfiddle
edit: suggestion from the comments:
this way, it wont throw an error when
s.length
is greater thann
edit2: suggestion from the comments:
this way, you can use the function for strings and non-strings alike.
Here is a JavaScript function that adds specified number of paddings with custom symble. the function takes three parameters.
I think its better to avoid recursion because its costly.
Based on the best answers of this question I have made a prototype for String called padLeft (exactly like we have in C#):
Usage:
JsFiddle
If you just want a very simple hacky one-liner to pad, just make a string of the desired padding character of the desired max padding length and then substring it to the length of what you want to pad.
Example: padding the string store in
e
with spaces to 25 characters long.Result:
"hello "
If you want to do the same with a number as input just call
.toString()
on it before.