Skip to content

Instantly share code, notes, and snippets.

@MorningZ
Last active April 11, 2019 16:01
Show Gist options
  • Save MorningZ/0d474d3d81d37f1f160e9efb44a565cd to your computer and use it in GitHub Desktop.
Save MorningZ/0d474d3d81d37f1f160e9efb44a565cd to your computer and use it in GitHub Desktop.
JavaScript prototypes
/* Prototypes that work against primitives */
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
String.prototype.contains = function(t) { return this.indexOf(t) >= 0 ? true : false; };
String.prototype.beginsWith = function(t, i) { if (i == false) { return (t == this.substring(0, t.length)); } else { return (t.toLowerCase() == this.substring(0, t.length).toLowerCase()); } };
String.prototype.startsWith = function(t, i) { if (i == false) { return (t == this.substring(0, t.length)); } else { return (t.toLowerCase() == this.substring(0, t.length).toLowerCase()); } };
String.prototype.endsWith = function(t, i) { if (i == false) { return (t == this.substring(this.length - t.length)); } else { return (t.toLowerCase() == this.substring(this.length - t.length).toLowerCase()); } };
String.prototype.format = function() {
var a = arguments;
if (a && a["0"] && a["0"] === "phone") {
var input = ("" + this).numbers();
switch(input.length) {
case 10:
return "(" + input.substr(0, 3) + ") " + input.substr(3, 3) + "-" + input.substr(6, 4);
case 11:
if (input.startsWith("1")) {
input = input.substr(1, 10);
return "(" + input.substr(0, 3) + ") " + input.substr(3, 3) + "-" + input.substr(6, 4);
}
case 12:
if (input.startsWith("+1")) {
input = input.substr(2, 10);
return "(" + input.substr(0, 3) + ") " + input.substr(3, 3) + "-" + input.substr(6, 4);
}
default:
}
return input; // No matches
}
else {
a["{"] = "{"; a["}"] = "}";
return this.replace(/{({|}|-?[0-9]+)}/g, function(c) { var b = a[c.substring(1, c.length - 1)]; return typeof b == "undefined" ? "" : b })
}
};
Array.prototype.contains = function(val) { return this.includes(val); };
String.prototype.numbers = function(a) {
var hit = ("" + this).trim().match(/\d+/g);
if (hit) {
return a ? hit.map(Number) : hit.map(Number).join('');
}
else {
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment