Last active
January 19, 2017 18:17
-
-
Save bmcminn/189c74f177bb1e06a661c9cfaf495117 to your computer and use it in GitHub Desktop.
Attempt at a Global String.pad method set:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Pads the left side of a string to `length` with N `char` characters | |
* @note If the string.length is greater than length, the method will not truncate to length | |
* @param {int} length The length of the desired string result | |
* @param {str} char Character to pad the string with | |
* @return {string} The padded string | |
*/ | |
String.prototype.padLeft = function(length, char) { | |
char = char || ' '; | |
length += 1; // TODO: figure out why we get an off by one error when returning str + pad | |
// remove leading/trailing spaces | |
var str = this.toString().trim(); | |
console.log(length, ' | ', str.length); | |
var pad = length - str.length < 0 ? '' : new Array(length - str.length).join(char); | |
console.log(length - str.length, ' | ', str.length); | |
return pad + str; | |
} | |
/** | |
* Pads the right side of a string to `length` with N `char` characters | |
* @note If the string.length is greater than length, the method will not truncate to length | |
* @param {int} length The length of the desired string result | |
* @param {str} char Character to pad the string with | |
* @return {string} The padded string | |
*/ | |
String.prototype.padRight = function(length, char) { | |
char = char || ' '; | |
length += 1; // TODO: figure out why we get an off by one error when returning str + pad | |
// remove leading/trailing spaces | |
var str = this.toString().trim(); | |
console.log(length, ' | ', str.length); | |
var pad = length - str.length < 0 ? '' : new Array(length - str.length).join(char); | |
console.log(length - str.length, ' | ', str.length); | |
return str + pad; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment