toSnakeCase method
Converts the string to snake_case (e.g., "Hello World" -> "hello_world").
Replaces spaces and special characters with underscores and converts to lowercase.
Example:
"Hello World".toSnakeCase(); // Returns "hello_world"
"camelCaseText".toSnakeCase(); // Returns "camel_case_text"
Implementation
String toSnakeCase() {
if (isEmpty) return this;
final buffer = StringBuffer();
final trimmed = trim();
bool isFirst = true;
for (int i = 0; i < trimmed.length; i++) {
final char = trimmed[i];
if (RegExp(r'[A-Z]').hasMatch(char)) {
if (!isFirst) buffer.write('_');
buffer.write(char.toLowerCase());
} else if (RegExp(r'\s+').hasMatch(char)) {
buffer.write('_');
} else if (RegExp(r'[a-z0-9]').hasMatch(char)) {
buffer.write(char.toLowerCase());
}
isFirst = false;
}
return buffer.toString();
}