Skip to content

Instantly share code, notes, and snippets.

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