Add camel, kebab and snake snippets

This commit is contained in:
Angelos Chalaris
2019-08-21 08:59:54 +03:00
parent 57b6b35539
commit 81c67efff9
3 changed files with 76 additions and 0 deletions

26
snippets/camel.md Normal file
View File

@ -0,0 +1,26 @@
---
title: camel
tags: string,regexp,intermediate
---
Converts a string to camelcase.
Break the string into words and combine them capitalizing the first letter of each word, using a regexp.
```py
import re
def camel(str):
s = re.sub(r"(\s|_|-)+","",
re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(),str)
)
return s[0].lower() + s[1:]
```
```py
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'
```

25
snippets/kebab.md Normal file
View File

@ -0,0 +1,25 @@
---
title: kebab
tags: string,regexp,intermediate
---
Converts a string to kebab case.
Break the string into words and combine them adding `-` as a separator, using a regexp.
```py
import re
def kebab(str):
return re.sub(r"(\s|_|-)+","-",
re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
lambda mo: mo.group(0).lower(),str)
)
```
```py
kebab('camelCase'); # 'camel-case'
kebab('some text'); # 'some-text'
kebab('some-mixed_string With spaces_underscores-and-hyphens'); # 'some-mixed-string-with-spaces-underscores-and-hyphens'
kebab('AllThe-small Things'); # "all-the-small-things"
```

25
snippets/snake.md Normal file
View File

@ -0,0 +1,25 @@
---
title: snake
tags: string,regexp,intermediate
---
Converts a string to snake case.
Break the string into words and combine them adding `_-_` as a separator, using a regexp.
```py
import re
def snake(str):
return re.sub(r"(\s|_|-)+","-",
re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
lambda mo: mo.group(0).lower(),str)
)
```
```py
snake('camelCase'); # 'camel_case'
snake('some text'); # 'some_text'
snake('some-mixed_string With spaces_underscores-and-hyphens'); # 'some_mixed_string_with_spaces_underscores_and_hyphens'
snake('AllThe-small Things'); # "all_the_smal_things"
```