Last active
August 29, 2015 13:57
-
-
Save mgamba/9611967 to your computer and use it in GitHub Desktop.
convert camelcase to snakecase in coffeescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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