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);

</script>

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




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

4 comments:

Test 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

Test said...

Suprotim,

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.