removeSpecialCharacters method

String removeSpecialCharacters([
  1. bool removeSpaces = false
])

Removes all non-alphanumeric characters, leaving spaces or joining words.

If removeSpaces is false (default), spaces separate words. If true, all whitespace is removed and words are joined into a single string. Hyphens are preserved if they connect word characters.

Example:

'Hello, World! 123.'.removeSpecialCharacters()        // 'Hello World 123'
'Hello, World! 123.'.removeSpecialCharacters(true)    // 'HelloWorld123'
'well-being'.removeSpecialCharacters()                // 'well being' (hyphen removed)

Implementation

String removeSpecialCharacters([bool removeSpaces = false]) {
  var result = trim();
  if (result.isEmpty) return '';

  result = replaceAll('_', ' ')
          .replaceAll(RegExp('[^$wordChars\\s]+'), ' ')
          .replaceAll(RegExp(r'\s+'), ' ')
          .trim();

  return removeSpaces ? result.replaceAll(RegExp(r'\s+'), '') : result;
}