2

e.g.

I want to write a camelToSnake()

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

is there such options

1
  • No, you can't do like \L$1 in javascript. Commented Oct 22, 2014 at 19:42

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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)
That's not true it is just reversing the case so it converts lowercase to uppercase and viceversa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.