slugify method

String slugify({
  1. String separator = '-',
})

Converts the string to a URL/filename-friendly slug.

Example: "Hello, World!" => "hello-world"

Implementation

String slugify({String separator = '-'}) {
  if (separator.isEmpty) {
    throw ArgumentError('Separator must not be empty');
  }

  final normalized = normalizeWhitespace().toLowerCase();
  if (normalized.isEmpty) return '';

  final escapedSeparator = RegExp.escape(separator);
  final cleaned = normalized
      .replaceAll(RegExp(r'[^a-z0-9\s_-]'), '')
      .replaceAll(RegExp(r'[_\s]+'), separator)
      .replaceAll(RegExp('$escapedSeparator+'), separator)
      .replaceAll(RegExp('^$escapedSeparator|$escapedSeparator\$'), '');

  return cleaned;
}