expandFunctionName method

String expandFunctionName()

Expands a compacted identifier into human-readable words.

Handles snake_case, kebab-case, camelCase, and PascalCase formats, converting them into space-separated words. Multiple spaces are collapsed, and the result is trimmed.

Useful for converting identifier names (variable names, enum values, etc.) into labels for UI or error messages.

Example:

'hello_world'.expandFunctionName()           // 'hello world'
'helloWorld'.expandFunctionName()            // 'hello World'
'HTTPServer'.expandFunctionName()            // 'HTTP Server'
'my-kebab-case'.expandFunctionName()         // 'my kebab case'
'snake_case_example'.expandFunctionName()    // 'snake case example'

Implementation

String expandFunctionName() {
  if (this.isEmpty) return this;

  // 1) replace separators with spaces
  // This regex targets underscores and hyphens as word separators.
  var t = replaceAll(RegExp(r'[_\-]+'), ' ');

  // 2) insert space between lower->upper transitions (camel/pascal)
  // This RegExp matches a lowercase letter or digit followed by an uppercase letter (splits camelCase and PascalCase transitions).
  t = t.replaceAllMapped(RegExp(r'([a-z0-9])([A-Z])'), (m) => '${m[1]} ${m[2]}');

  // 3) split sequences of capitals followed by lower (e.g., "HTTPServer" -> "HTTP Server")
  // This regex splits acronyms from following capitalized words, e.g., "HTTPServer" becomes "HTTP Server".
  t = t.replaceAllMapped(RegExp(r'([A-Z]+)([A-Z][a-z])'), (m) => '${m[1]} ${m[2]}');

  // 4) collapse multiple spaces and trim
  t = t.replaceAll(RegExp(r'\s+'), ' ').trim();

  return t;
}