So I was messing with a little template builder, and decided to try and dynamically read and write CSS to elements on a page. This brought up the difference between JavaScript having camel case representations of the dashed css properties. Soooooo, I had to write little string functions to convert camel case to dashed strings and visa versa. Heres what I came up with:
Trim String
1 2 3 | String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g, ""); }; |
To Camel Case
1 2 3 | String.prototype.toCamel = function(){ return this.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');}); }; |
To Dashed from Camel Case
1 2 3 | String.prototype.toDash = function(){ return this.replace(/([A-Z])/g, function($1){return "-"+$1.toLowerCase();}); }; |
To Underscore from Camel Case
1 2 3 | String.prototype.toUnderscore = function(){ return this.replace(/([A-Z])/g, function($1){return "_"+$1.toLowerCase();}); }; |
Enjoy!


The brackets in the regex can be removed. The naming of the variable as $1 is misleading as the inline function is being passed the regex match, and not the back reference.
awesome, thanks for the suggestions =) I’m not very good at regex….
Great collection of string manipulation functions, cheers.
god i hate regex
Very useful! Thanks.
+1
#timesaver