import re
import html
def normalize_whitespace(s: str | None) -> str:
if not s:
return ""
return re.sub(r"\s+", " ", s).strip()
def truncate(s: str, max_len: int, ellipsis: str = "...") -> str:
if len(s) <= max_len:
return s
return s[: max_len - len(ellipsis)] + ellipsis
def strip_html_tags(s: str | None) -> str:
if not s:
return ""
# Unescape HTML entities first
s = html.unescape(s)
# Remove tags
s = re.sub(r"<[^>]+>", " ", s)
return normalize_whitespace(s)
def slugify(s: str) -> str:
s = s.lower().strip()
s = re.sub(r"[^\w\s-]", "", s)
s = re.sub(r"[\s_-]+", "-", s)
return s