toSnakeCase function

String toSnakeCase(
  1. String text
)

String utility functions for naming conventions. Converts any string (PascalCase, camelCase, kebab-case, space separated) to snake_case.

Implementation

String toSnakeCase(String text) {
  if (text.isEmpty) return "";

  return text
      .replaceAllMapped(RegExp(r'([a-z0-9])([A-Z])'), (Match m) => '${m[1]}_${m[2]}')
      .replaceAllMapped(RegExp(r'([A-Z])([A-Z][a-z])'), (Match m) => '${m[1]}_${m[2]}')
      .replaceAll(RegExp(r'[-\s]'), '_')
      .replaceAll(RegExp(r'[^a-zA-Z0-9_]'), '') // Remove other special chars but KEEP underscores
      .toLowerCase();
}