2

e.g.

I want to write a camelToSnake()

camelToSnake = (phrase) ->
  return phrase.replace(/([A-Z])/g, /-\L$1/)

is there such options

user2167582
  • 5,986
  • 13
  • 64
  • 121

1 Answers1

1

You can use this code:

var s = 'camelToSnake';
var r = s.replace(/([A-Za-z])/g, function ($0, $1) { c=$1.charAt(0);
          return (c==c.toUpperCase())?c.toLowerCase():c.toUpperCase(); } );
//=> CAMELtOsNAKE
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Wouldn't the callback for snake case look more like this? function ($0, $1) { c=$1.charAt(0); return '-' + c.toLowerCase() } ); Or am I misunderstanding snake-case? (Also meant to mention the regex would only check upper-case letters) – Wet Noodles Oct 22 '14 at 19:41
  • That's not true it is just reversing the case so it converts lowercase to uppercase and viceversa. – anubhava Oct 22 '14 at 19:45