Skip to content

Instantly share code, notes, and snippets.

@cfleschhut
Created June 5, 2011 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cfleschhut/1009258 to your computer and use it in GitHub Desktop.
Save cfleschhut/1009258 to your computer and use it in GitHub Desktop.
JavaScript Snippets: Augmented Native Objects
String.augmentedProperties = [];
if (!String.prototype.camelize) {
String.prototype.camelize = function() {
return this.replace(/(\s)([a-zA-Z])/g, function(str, p1, p2) {
return p2.toUpperCase();
});
};
String.augmentedProperties.push("camelize");
}
if (!String.prototype.reverse) {
String.prototype.reverse = function() {
return this.split("").reverse().join("");
};
String.augmentedProperties.push("reverse");
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
String.augmentedProperties.push("trim");
}
Array.augmentedProperties = [];
if (!Array.prototype.inArray) {
Array.prototype.inArray = function(needle) {
for(var i=0; i<this.length; i++) {
if (this[i] == needle) {
return true;
}
}
return false;
};
Array.augmentedProperties.push("inArray");
}
@FabianBeiner
Copy link

Here a version without regex, just in case. :) Then again, regex will be faster here...

String.prototype.camelize = function() {
  return this.split(" ").map( function(w) { return w.substr(0, 1).toUpperCase() + w.substr(1); } ).join("");
}

But why do you want to return the empty string, I think that's useless here:

String.prototype.camelize = function() {
  return this.replace(/(\s)([a-zA-Z])/g, function(str, p1, p2) {
    return p2.toUpperCase();
  });
};

@cfleschhut
Copy link
Author

Nice addition, thanks! I updated the camelize method.

@cfleschhut
Copy link
Author

complete, comprehensive collection => http://sugarjs.com/api

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment