toSlug method
Converts this string to a URL-safe slug (lowercase, spaces/special → hyphen).
Replaces whitespace and non-alphanumeric characters with a single hyphen, trims leading/trailing hyphens, and returns lowercase. Empty or whitespace-only strings return empty.
Example:
'Hello World!'.toSlug(); // 'hello-world'
' déjà vu '.toSlug(); // 'd-j-vu' (diacritics not normalized)
'one___two'.toSlug(); // 'one-two'
Implementation
@useResult
String toSlug() {
if (isEmpty) return this;
final String trimmed = trim();
if (trimmed.isEmpty) return '';
final String collapsed = trimmed
.toLowerCase()
.replaceAll(RegExp(r'[\s_\-]+'), '-')
.replaceAll(RegExp(r'[^a-z0-9\-]'), '-')
.replaceAll(RegExp(r'-+'), '-');
return collapsed.replaceAll(RegExp(r'^-+|-+$'), '');
}