Pad Left or Right Using JavaScript

String Padding in JavaScript

// Pad Right
String.prototype.padRight = function (l, c) {
    return this + Array(l - this.length + 1).join(c || " ");
}

// Pad Left
String.prototype.padLeft = function (l, c) {
    return Array(l - this.length + 1).join(c || " ") + this;
}

// Print
var print = function (val) {
    document.body.innerHTML = document.body.innerHTML + "<br />" + val
}
// Function Call
print("String Padding Right Side".padRight(40, "!"))
print("Text Padding ".padRight(20, "Right ") + "<br />")

print("Javascript Pad ".padLeft(20, "Left "))
print("Javascript Left ".padLeft(25, "Pad "))
DEMO
Pad Left or Right Using JavaScript Pad Left or Right Using JavaScript Reviewed by Bhaumik Patel on 7:19 PM Rating: 5