Files
30-seconds-of-code/snippets/kebab.md
2019-08-21 08:59:54 +03:00

631 B

title, tags
title tags
kebab string,regexp,intermediate

Converts a string to kebab case.

Break the string into words and combine them adding - as a separator, using a regexp.

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)
  )
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"