toSnakeCase method

String toSnakeCase()

Converts this string to snake_case

Example:

print('Hello World'.toSnakeCase()); // "hello_world"
print('HelloWorld'.toSnakeCase()); // "hello_world"

Implementation

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

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

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

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