asWords method

String asWords()

Extracts words from the string, preserving hyphenated compounds.

Removes punctuation and special characters while keeping word-like structures (letters, digits, hyphens). Collapses multiple spaces and returns the cleaned result.

Useful for extracting searchable words or normalising user input before splitting.

Example:

'Hello, World!'.asWords()          // 'Hello World'
'well-being matters'.asWords()     // 'well-being matters'
'foo123bar!'.asWords()             // 'foo123bar'
'  spaced   out  '.asWords()       // 'spaced out'

Implementation

String asWords() {
  var cleaned = replaceAll(RegExp('[^$wordChars\\s-]'), ' ')
      .replaceAll(RegExp(r'\s+'), ' ')
      .trim();

  // Collapse multiple consecutive hyphens to single hyphen
  cleaned = cleaned.replaceAll(RegExp('-+'), '-');

  // Remove hyphens that don't connect letters
  cleaned = cleaned.replaceAll(RegExp('-(?![a-zA-Z])|(?<![a-zA-Z])-'), ' ');

  // Collapse multiple spaces again
  cleaned = cleaned.replaceAll(RegExp(r'\s+'), ' ').trim();

  return cleaned.split(RegExp(r'\s+'))
      .where((word) => word.isNotEmpty)
      .join(' ');
}