Almost a month ago, I posted about creating a camel case function in VBScript. Now I think it is time to see a simple way to implement this function in JavaScript:

String.prototype.toCamelCase = function(cap1st) {
  return ((cap1st ? "-" : "") + this).replace(/-+([^-])/g, function(a, b) {
    return b.toUpperCase();
  });
};

Believe it or not, that is all the code you will need for the following to work:

alert("back-color".toCamelCase()); // backColor
alert("-moz-opacity".toCamelCase()); // MozOpacity
alert("border-color-left".toCamelCase()); // borderColorLeft
alert("dragon-ball-z".toCamelCase(true)); // DragonBallZ
alert("z-index".toCamelCase()); // zIndex

You will notice that our new function is similar to Prototype’s String.prototype.camelize() function. One thing that it offers which is not offered in Prototype is the ability to pass an argument which evaluates to true in order to always capitalize the first letter. My main motivation for adding this feature was the Wikipedia page on this subject. If you want to use this function without downloading an entire library, feel free to use this function definition. 8)


1 Comment

Chris West's Blog » Camel Case In JavaScript · August 10, 2011 at 7:09 PM

[…] Read more: Chris West's Blog » Camel Case In JavaScript […]

Leave a Reply to Chris West's Blog » Camel Case In JavaScript Cancel reply

Your email address will not be published. Required fields are marked *