removeSingleCharacterWords method

String? removeSingleCharacterWords({
  1. bool trim = true,
  2. bool removeMultipleSpaces = true,
})

Removes single-character words (letters and digits) from this string.

Uses Unicode-aware matching to remove standalone single-character words, including both letters (\p{L}) and digits (\p{N}). A "word" is defined as a single character surrounded by whitespace or at the start/end of the string.

Args:

  • trim: If true (default), trims leading/trailing whitespace from the result.
  • removeMultipleSpaces: If true (default), collapses consecutive spaces into one.

Returns: The modified string, or null if the result is empty.

Example:

'a hello world'.removeSingleCharacterWords(); // 'hello world'
'I am 5 years old'.removeSingleCharacterWords(); // 'am years old'
'你 好 test'.removeSingleCharacterWords(); // 'test' (Unicode aware)
'x y z'.removeSingleCharacterWords(); // null (all removed)

Implementation

String? removeSingleCharacterWords({bool trim = true, bool removeMultipleSpaces = true}) {
  if (isEmpty) return this;
  String result = removeAll(_singleCharWordRegex);
  if (removeMultipleSpaces) {
    result = result.replaceAll(RegExp(r'\s+'), ' ');
  }
  if (trim) {
    result = result.trim();
  }
  return result.isEmpty ? null : result;
}