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

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!

10 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

    +1
    #timesaver

  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

    toCamel
    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.

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=""> <strike> <strong>