Pad //JavaScript Repository

Description

Concatenates a substring until the determinated length is reached without loops.
Created: 2005.11.20

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/string/pad [rev. #1]

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 (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>

Help

String.pad(length: Integer, [substring: String = " "], [type: Integer = 0]): String
Returns the string with a substring padded on the left, right or both sides.
length
amount of characters that the string must have
substring
string that will be concatenated
type
specifies the side where the concatenation will happen, where: 0 = left, 1 = right and 2 = both sides

Rank (Votes: 48)

3.52