breakLongWords method
Inserts separator (e.g. soft hyphen) every charCount graphemes within long words.
Only inserts inside "words" (runs of non-whitespace). charCount must be positive.
Counts grapheme clusters, so an emoji or a letter plus combining mark is
one character and is never split by an inserted separator.
Returns the string with separators inserted in long words.
Throws ArgumentError if charCount is not positive.
Example:
'hello'.breakLongWords(2, '-'); // 'he-ll-o'
'\ud83d\udc4b\ud83d\udc4b\ud83d\udc4b'.breakLongWords(2, '-'); // '\ud83d\udc4b\ud83d\udc4b-\ud83d\udc4b'
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
String breakLongWords(int charCount, String separator) {
if (charCount < 1) {
throw ArgumentError(_kErrCharCountPositive, _kParamCharCount);
}
if (isEmpty) return this;
final List<String> wordsList = split(RegExp(r'\s+')).toList();
if (wordsList.isEmpty) return this;
final List<String> result = List<String>.filled(wordsList.length, '');
final StringBuffer sb = StringBuffer();
int idx = 0;
for (final String word in wordsList) {
// Measure and slice by grapheme. The old loop stepped over code-unit
// `length` but sliced with grapheme-indexed substringSafe, so emoji words
// were broken at the wrong points and gained empty trailing segments.
final Characters chars = word.characters;
if (chars.length <= charCount) {
result[idx++] = word;
} else {
sb.clear();
for (int i = 0; i < chars.length; i += charCount) {
if (i > 0) sb.write(separator);
final int end = (i + charCount).clamp(0, chars.length);
sb.write(chars.getRange(i, end).string);
}
result[idx++] = sb.toString();
}
}
return result.sublist(0, idx).join(' ');
}