Files
30-seconds-of-code/snippets/camel.md
Angelos Chalaris af91bb1695 Update camel.md
2019-10-31 09:36:39 +02:00

787 B

title, tags
title tags
camel string,regexp,intermediate

Converts a string to camelcase.

Use re.sub() to replace any -,_ or (space) with a space, using the regexp r"(_|-)+". Use title() to capitalize the first letter of each word convert the rest to lowercase. Finally, use replace() to remove spaces between words.

import re

def camel(s):
  s = re.sub(r"(_|-)+", " ", s).title().replace(" ", "")
  return s[0].lower() + s[1:]
camel('some_database_field_name'); # 'someDatabaseFieldName'
camel('Some label that needs to be camelized'); # 'someLabelThatNeedsToBeCamelized'
camel('some-javascript-property'); # 'someJavascriptProperty'
camel('some-mixed_string with spaces_underscores-and-hyphens'); # 'someMixedStringWithSpacesUnderscoresAndHyphens'