Files
30-seconds-of-code/snippets/kebab.md
Isabelle Viktoria Maciohsek b3b60cd838 Update snippet titles
2022-02-13 14:18:08 +02:00

31 lines
899 B
Markdown

---
title: Kebabcase string
tags: string,regexp,intermediate
firstSeen: 2019-08-21T08:59:54+03:00
lastUpdated: 2020-11-02T19:28:05+02:00
---
Converts a string to kebab case.
- Use `re.sub()` to replace any `-` or `_` with a space, using the regexp `r"(_|-)+"`.
- Use `re.sub()` to match all words in the string, `str.lower()` to lowercase them.
- Finally, use `str.join()` to combine all word using `-` as the separator.
```py
from re import sub
def kebab(s):
return '-'.join(
sub(r"(\s|_|-)+"," ",
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(), s)).split())
```
```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'
```