Skip to content

Instantly share code, notes, and snippets.

@mgamba
Last active August 29, 2015 13:57
Show Gist options
  • Save mgamba/9611967 to your computer and use it in GitHub Desktop.
Save mgamba/9611967 to your computer and use it in GitHub Desktop.
convert camelcase to snakecase in coffeescript
obj = {'someThing':'else',"BlahBlah":"bLah","sealTeam":6}
defaults = {'some_thing':'more',"seal_team":2}
camelToSnake = (s)->
s = s.replace /^([A-Z]+)/, (match) ->
if match.length == 1
match.toLowerCase()
else
"#{match.slice(0,match.length-1).toLowerCase()}_#{match.slice(match.length-1).toLowerCase()}"
s = s.replace /([A-Z]+)$/, (match) ->
"_#{match.toLowerCase()}"
s = s.replace /([A-Z]+)/g, (match) ->
if match.length == 1
"_#{match.toLowerCase()}"
else
"_#{match.slice(0,match.length-1).toLowerCase()}_#{match.slice(match.length-1).toLowerCase()}"
for key of obj
defaults[camelToSnake(key)] = obj[key]
console.log defaults
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment