replaceLineBreaks method
Replaces all line breaks (\n) with a specified string.
When deduplicate is true, collapses consecutive runs of the replacement
string into a single occurrence. This uses a non-capturing group regex to
handle any replacement string, including those with special regex characters.
Args:
replacement: The string to replace line breaks with. Null or empty removes line breaks.deduplicate: If true (default), collapses consecutive replacement sequences.
Returns: The string with line breaks replaced and optionally deduplicated.
Example:
'a\n\nb'.replaceLineBreaks(' '); // 'a b' (deduplicated)
'a\n\nb'.replaceLineBreaks('+'); // 'a+b'
'a\n\nb'.replaceLineBreaks('.*'); // 'a.*b' (special chars handled)
'a\n\nb'.replaceLineBreaks(' ', deduplicate: false); // 'a b'
Implementation
String replaceLineBreaks(String? replacement, {bool deduplicate = true}) {
final String result = replaceAll(_lineBreakRegex, replacement ?? '');
if (deduplicate && replacement != null && replacement.isNotEmpty) {
final String pattern = '(?:${RegExp.escape(replacement)})+';
final RegExp r = RegExp(pattern);
return result.replaceAll(r, replacement);
}
return result;
}