toKebabCase method

String toKebabCase()

Converts this string to kebab-case

Example:

print('Hello World'.toKebabCase()); // "hello-world"
print('HelloWorld'.toKebabCase()); // "hello-world"

Implementation

String toKebabCase() {
  if (isEmpty) return this;

  // First, handle spaces and underscores by replacing them with hyphens
  String result = replaceAll(RegExp(r'[\s_]+'), '-');

  // Then handle camelCase/PascalCase by adding hyphens before capital letters
  // but avoid duplicate hyphens
  result = result.replaceAllMapped(
    RegExp(r'([a-z])([A-Z])'),
    (match) => '${match.group(1)}-${match.group(2)}',
  );

  // Convert to lowercase and clean up any duplicate hyphens
  return result
      .toLowerCase()
      .replaceAll(RegExp(r'-+'), '-')
      .replaceAll(RegExp(r'^-|-$'), '');
}