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

4 comments:

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

    ReplyDelete
  2. 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

    ReplyDelete
  3. 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

    ReplyDelete