Skip to content

Instantly share code, notes, and snippets.

@tristanjahier
Created March 22, 2017 16:08
Show Gist options
  • Save tristanjahier/1d32223f198f143e676ac0248b123389 to your computer and use it in GitHub Desktop.
Save tristanjahier/1d32223f198f143e676ac0248b123389 to your computer and use it in GitHub Desktop.
Simple functions to change the case of a string
toSpaceCase = (str) ->
str.replace(/[\W_]+(.|$)/g, (x, y) -> " #{y ? ''}").trim()
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
.toLowerCase()
toSnakeCase = (str) ->
toSpaceCase(str).replace(/\s/g, '_')
toCamelCase = (str) ->
toSpaceCase(str).replace(/\s(\w)/g, (x, y) -> y.toUpperCase())
toPascalCase = (str) ->
toSpaceCase(str).replace(/(?:^|\s)(\w)/g, (x, y) -> y.toUpperCase())
toDashCase = (str) ->
toSpaceCase(str).replace(/\s/g, '-')
toDotCase = (str) ->
toSpaceCase(str).replace(/\s/g, '.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment