Alignment function

Javascript left or right alignment script, with overflow control.

/* Function snipper by Ken Engström, http://ken.nu */
function adjust(string, size, turn) {
    "use strict";
    string = string.toString().substring(0, (string.length < size) ? string.length : size);
    var noOfBlanks = size - string.length, blanks = "";
    while (blanks.length < noOfBlanks && noOfBlanks > 0) { blanks += " "; }
    return [string, string + blanks, blanks + string][(turn === 1 || turn === 2) ? +turn : 0];
}

string string // “the string you want to align”;
size int // positive number for the final length of the string.
turn int /*
1 for left align, adds spaces to the right.
2 for right align, adds spaces to the left.
0 will ensure the string is never longer then size, without alignment.
*/
adjust(string, size, turn)

This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *