Skip to content

Instantly share code, notes, and snippets.

@MorningZ
Created May 6, 2011 05:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MorningZ/958481 to your computer and use it in GitHub Desktop.
Save MorningZ/958481 to your computer and use it in GitHub Desktop.
Helpful 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.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()); } };
Object.prototype.merge = (function (ob) {var o = this;var i = 0;for (var z in ob) {if (ob.hasOwnProperty(z)) {o[z] = ob[z];}}return o;});
/* Examples:
var s = ' I have white space ';
s.trim() ---> 'I have white space'
s.contains("white") ----> true
s.contains("blue") ----> false
s.beginsWith("I") ----> false
s.trim().beginsWith("I") ----> true
s.endsWith("space") ----> false
s.trim().endsWith("space") ----> true
var a = { "Color" : "Red", "Size" : "Large" };
var b = { "Color" : "Green", "Opens" : "Left" };
a.merge(b) ---> a would now be: { "Color" : "Green", "Size" : "Large", "Opens" : "Left" }
or if you merged a into b
b.merge(a) ---> b would now be: { "Color" : "Red", "Size" : "Large", "Opens" : "Left" }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment