I need this all the time and am constantly frustrated that the Trim(), TrimStart() and TrimEnd() functions don\'t take strings as inputs. You call EndsWith() on a string, an
Here's the extension method I came up with (heavy inspiration taken from existing answers to this question) to complement the existing TrimEnd method; it takes an optional bool allowing for only removing one trailing instance of the string instead of all trailing instances.
///
/// Removes trailing occurrence(s) of a given string from the current System.String object.
///
/// A string to remove from the end of the current System.String object.
/// If true, removes all trailing occurrences of the given suffix; otherwise, just removes the outermost one.
/// The string that remains after removal of suffix occurrence(s) of the string in the trimSuffix parameter.
public static string TrimEnd(this string input, string trimSuffix, bool removeAll = true) {
while (input != null && trimSuffix != null && input.EndsWith(trimSuffix)) {
input = input.Substring(0, input.Length - trimSuffix.Length);
if (!removeAll) {
return input;
}
}
return input;
}