normalizeLineBreaks method

  1. @useResult
String normalizeLineBreaks([
  1. String target = '\n'
])

Normalizes line breaks to target (default \n).

Replaces CRLF (\r\n), CR (\r), and LF (\n) with a single target character. target must not be null.

Returns a new string with normalized line breaks.

Throws ArgumentError if target is empty.

Example:

'a\r\nb\rc\n'.normalizeLineBreaks();  // 'a\nb\nc\n'
'a\r\nb'.normalizeLineBreaks('\r\n'); // 'a\r\nb' (CRLF)

Implementation

@useResult
String normalizeLineBreaks([String target = '\n']) {
  if (target.isEmpty) {
    throw ArgumentError(_kErrTargetNonEmpty, _kParamTarget);
  }
  if (isEmpty) return this;
  return replaceAll(RegExp(r'\r\n|\r|\n'), target);
}