Created
May 6, 2011 05:16
-
-
Save MorningZ/958481 to your computer and use it in GitHub Desktop.
Helpful JavaScript prototypes!
This file contains 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
/*********************************************/ | |
/* 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