Skip to content

Instantly share code, notes, and snippets.

@sposmen
Last active August 29, 2015 14:01
Show Gist options
  • Save sposmen/763ff178e140cae990ab to your computer and use it in GitHub Desktop.
Save sposmen/763ff178e140cae990ab to your computer and use it in GitHub Desktop.
Complete a string (number) to the specified length. Useful when you needs a formatted number as '00000123'
/**
* Generates a string length of a specific character
* @param char Character to repeat
* @param times How many times
* @returns {string}
*/
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
/**
* Completes a string to specified length with the specified char
* @param str
* @param length
* @param char
* @param toRight
* @returns {string}
*/
var completeToLength = function (str, length, char) {
char = char || "0";
return char.repeat(length - str.toString().length) + str;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment