Camel Case In JavaScript

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)

One thought on “Camel Case In JavaScript

  1. Pingback: Chris West's Blog ยป Camel Case In JavaScript

Leave a Reply

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


− 4 = three

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>