lychees's picture
Upload 569 files
87b3b3a
/**
* @returns {string} First letter capitalized
*/
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.substring(1);
}
/**
* Left pad
* @param {string} [character="0"]
* @param {int} [count=2]
*/
String.prototype.lpad = function(character, count) {
var ch = character || "0";
var cnt = count || 2;
var s = "";
while (s.length < (cnt - this.length)) { s += ch; }
s = s.substring(0, cnt-this.length);
return s+this;
}
/**
* Right pad
* @param {string} [character="0"]
* @param {int} [count=2]
*/
String.prototype.rpad = function(character, count) {
var ch = character || "0";
var cnt = count || 2;
var s = "";
while (s.length < (cnt - this.length)) { s += ch; }
s = s.substring(0, cnt-this.length);
return this+s;
}
/**
* Format a string in a flexible way. Scans for %s strings and replaces them with arguments. List of patterns is modifiable via String.format.map.
* @param {string} template
* @param {any} [argv]
*/
String.format = function(template) {
var map = String.format.map;
var args = Array.prototype.slice.call(arguments, 1);
var replacer = function(match, group1, group2, index) {
if (template.charAt(index-1) == "%") { return match.substring(1); }
if (!args.length) { return match; }
var obj = args[0];
var group = group1 || group2;
var parts = group.split(",");
var name = parts.shift();
var method = map[name.toLowerCase()];
if (!method) { return match; }
var obj = args.shift();
var replaced = obj[method].apply(obj, parts);
var first = name.charAt(0);
if (first != first.toLowerCase()) { replaced = replaced.capitalize(); }
return replaced;
}
return template.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi, replacer);
}
String.format.map = {
"s": "toString"
}
/**
* Convenience shortcut to String.format(this)
*/
String.prototype.format = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(this);
return String.format.apply(String, args);
}