Skip to content

Instantly share code, notes, and snippets.

@nicerobot
Created April 4, 2012 16:57
Show Gist options
  • Save nicerobot/2303834 to your computer and use it in GitHub Desktop.
Save nicerobot/2303834 to your computer and use it in GitHub Desktop.
JavaScript Object and String enhancements. Each usable standalone.
if (!Object.prototype.sizeof) {
Object.defineProperty(Object.prototype, 'sizeof', {
value: function() {
var counter = 0;
for (index in this) counter++;
return counter;
},
enumerable: false
});
}
if (!String.prototype.htmlEntities) {
Object.defineProperty(String.prototype, 'htmlEntities', {
value: function() {
return String(this).replace(/&/g, '&').replace(/>/g, '>').replace(/"/g, '"');
},
enumerable: false
});
}
if (!String.prototype.isHex) {
Object.defineProperty(String.prototype, 'isHex', {
value: function() {
return this.substring(0, 1) == '#' && (this.length == 4 || this.length == 7) && /^[0-9a-fA-F]+$/.test(this.slice(1));
},
enumerable: false
});
}
if (!String.prototype.pxToInt) {
Object.defineProperty(String.prototype, 'pxToInt', {
value: function() {
return parseInt(this.split('px')[0]);
},
enumerable: false
});
}
if (!String.prototype.reverse) {
Object.defineProperty(String.prototype, 'reverse', {
value: function() {
return this.split('').reverse().join('');
},
enumerable: false
});
}
if (!String.prototype.stripNonAlpha) {
Object.defineProperty(String.prototype, 'stripNonAlpha', {
value: function() {
return this.replace(/[^A-Za-z ]+/g, "");
},
enumerable: false
});
}
if (!String.prototype.stripTags) {
Object.defineProperty(String.prototype, 'stripTags', {
value: function() {
return this.replace(/<\/?[^>]+>/gi, '');
},
enumerable: false
});
}
if (!String.prototype.trim) {
Object.defineProperty(String.prototype, 'trim', {
value: function() {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
},
enumerable: false
});
}
if (!String.prototype.wordCount) {
Object.defineProperty(String.prototype, 'wordCount', {
value: function() {
return this.split(' ').length;
},
enumerable: false
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment