removeEndNullable method
Removes find from the end of this string, tolerating a null/empty
find, and signals "no source to strip from" with null.
The nullable-aware companion to removeEnd. The three-way result lets a
caller distinguish "stripped to nothing" ('') from "there was no source
string to strip" (null) — a distinction a plain String removeEnd
cannot express. Branch semantics:
- When
findisnullor empty, there is nothing to strip: returns this string unchanged (including when this string is itself empty). - When this string is empty AND
findis a real, non-empty suffix, returnsnull— an empty source cannot carry the requested suffix, sonull(rather than'') marks the "no source" case distinctly. This asymmetry is deliberate; do not "normalize" it to''. - Otherwise delegates to removeEnd, so only ONE trailing occurrence is
removed and a whole-string match strips to
''(NOTnull).
Matching is case-sensitive UTF-16 code-unit suffix matching (inherited from removeEnd/String.endsWith), NOT grapheme-aware: stripping a combining mark or a fragment of a surrogate pair can split a cluster.
Example:
'hello.txt'.removeEndNullable('.txt'); // 'hello'
'hello'.removeEndNullable(null); // 'hello' (nothing to strip)
'abc'.removeEndNullable('abc'); // '' (stripped to nothing)
''.removeEndNullable('x'); // null (no source to strip)
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
String? removeEndNullable(String? find) => find == null || find.isEmpty
? this
: isEmpty
? null
: removeEnd(find);