String Functions for Javascript – trim, to camel case, to dashed, and to underscore

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

String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g, "");

To Camel Case

String.prototype.toCamel = function(){
	return this.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});

To Dashed from Camel Case

String.prototype.toDash = function(){
	return this.replace(/([A-Z])/g, function($1){return "-"+$1.toLowerCase();});

To Underscore from Camel Case

String.prototype.toUnderscore = function(){
	return this.replace(/([A-Z])/g, function($1){return "_"+$1.toLowerCase();});


13 Comments to String Functions for Javascript – trim, to camel case, to dashed, and to underscore

  1. Sam Hall's Gravatar Sam Hall
    December 13, 2010 at 7:15 pm | Permalink

    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.

  2. June 30, 2011 at 7:42 pm | Permalink

    Great collection of string manipulation functions, cheers.

  3. August 2, 2011 at 3:49 am | Permalink

    god i hate regex

  4. April 13, 2012 at 5:11 am | Permalink

    Very useful! Thanks.

  5. April 24, 2013 at 5:43 am | Permalink


  6. Tom's Gravatar Tom
    July 29, 2013 at 3:39 pm | Permalink

    This work great thanks

  7. Mr. O's Gravatar Mr. O
    November 8, 2013 at 7:26 am | Permalink

    String.prototype.toCamel = function(){
    return this.replace(/([-_][a-z])/g, function($1){return $1.toUpperCase().replace(/[-_]/,'');});

  8. Mr. O's Gravatar Mr. O
    November 8, 2013 at 9:07 am | Permalink

    Above is a modified method to match “-” and “_” input strings.

  9. Dave's Gravatar Dave
    November 19, 2013 at 4:54 am | Permalink


  10. April 28, 2014 at 9:40 pm | Permalink

    Hello, I think your site could possibly be having browser compatibility issues.
    When I look at your blog in Safari, it looks fine however, if opening in Internet Explorer, it has some overlapping issues.
    I merely wanted to provide you with a quick heads up!
    Besides that, excellent blog!

  11. November 19, 2014 at 3:32 pm | Permalink

    It is perfect and the OOP approach is also elegant.
    Thank You.

Leave a Reply

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