JavaScript: Convert CamelCase to Dashes and vice-versa

My colleague Satyam shared a nice piece of JavaScript code that converts a camelcase to dashes and dashes to Camelcase.

For eg: if the string has a camelcase in it - like ‘viceVersa’, the result expected is ‘vice-Versa’. Similarly if a string has a dash in it, like ‘dot-net’, the result expected is ‘dotNet’. Let’s see the piece of code to make this possible:

<script type="text/javascript" language="javascript">
   function camelToDash(str) {
      return str.replace(/\W+/g, '-')
                .replace(/([a-z\d])([A-Z])/g, '$1-$2');

   function dashToCamel(str) {
         return str.replace(/\W+(.)/g, function (x, chr) {
                          return chr.toUpperCase();

   var str1 = "devCurry"; 
   str1 = camelToDash(str1);
   var str2 = "dev-curry";
   str2 = dashToCamel(str2);
   alert(str1 + " " + str2);


Let’s see some important bits of the code shown above.

The /\W+/ pattern matches one or more of any of A-Z, a-z, 0-9, and the underscore character. The "g" (global) flag specifies that the search should find all occurrences of the pattern. The $1,$2,… property represents parenthesized substring matches.

Run the code and you should see the following output

JavaScript camelcase

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


Elijah Manor said...

Nice Regex-fu ;)

You might consider showing another example of the camelToDash code replacing any whitespace with a dash as it is doing. Like camelToDash( "dev Curry" ) outputting "dev-Curry"

Also, there is a typo describing the /\W+/ in the paragraph. It should say something to the fact that it "matches any character that is NOT a word character (alphanumeric or underscore)"

Have a great day... or night for you ;)

Suprotim Agarwal said...

Elijah, Thanks for your comment. The code does replace whitespaces with dashes. Did you mean a dedicated function just for the whitespaces? Let me know if you meant anything else

Elijah Manor said...


Ohh no, I just meant to say your code does more than your examples show and was suggesting you could add another example to demonstrate it like...

var str3 = "dev Curry";
str3 = camelToDash( str3 ); //dev-Curry

Suprotim Agarwal said...

Sorry my bad! Thanks.