toCamelCaseAcronyms method

  1. @useResult
String toCamelCaseAcronyms()

Converts to camelCase, lowercasing acronyms (e.g. HTTPResponse → httpResponse).

Splits on non-alpha, then capitalizes each word except the first (lowercase). Consecutive uppercase letters are treated as one acronym and lowercased as a unit.

Returns the camelCase string.

Example:

'HTTP response'.toCamelCaseAcronyms();  // 'httpResponse'

Implementation

@useResult
String toCamelCaseAcronyms() {
  if (isEmpty) return this;
  final List<String> words = split(
    RegExp(r'[^a-zA-Z]+'),
  ).where((String word) => word.isNotEmpty).toList();
  if (words.isEmpty) return '';
  final StringBuffer sb = StringBuffer(words[0].toLowerCase());
  for (int i = 1; i < words.length; i++) {
    final String word = words[i];
    if (word.length > 1) {
      final String rest = word.substringSafe(1);
      // A fully-uppercase word is treated as a single acronym and lowercased
      // whole (HTTP -> http), instead of title-casing it to "Http".
      final bool allUpper = word.toUpperCase() == word;
      if (allUpper) {
        sb.write(word.toLowerCase());
      } else {
        const int firstCharIndex = 0;
        final String firstChar = word[firstCharIndex];
        sb
          ..write(firstChar.toUpperCase())
          ..write(rest.toLowerCase());
      }
    } else {
      sb.write(word.toUpperCase());
    }
  }
  return sb.toString();
}