Skip to content

Add trim_prefix and trim_suffix methods for both slice and str types. #142331

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

deven
Copy link

@deven deven commented Jun 11, 2025

Implements trim_prefix and trim_suffix methods for both slice and str types, which remove at most one occurrence of a prefix/suffix while always returning a string/slice (rather than Option), enabling easy method chaining.

Tracking issue

Closes #142312

API

impl str {
    pub fn trim_prefix<P: Pattern>(&self, prefix: P) -> &str;
    pub fn trim_suffix<P: Pattern>(&self, suffix: P) -> &str
    where
        for<'a> P::Searcher<'a>: ReverseSearcher<'a>;
}

impl<T> [T] {
    pub fn trim_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> &[T]
    where
        T: PartialEq;
    pub fn trim_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> &[T]
    where
        T: PartialEq;
}

Examples

// Method chaining
assert_eq!(" <https://example.com/> ".trim().trim_prefix('<').trim_suffix('>').trim(), "https://example.com/");

// Slices
let v = &[10, 40, 30];
assert_eq!(v.trim_prefix(&[10]), &[40, 30][..]);

ACP

Originally proposed in rust-lang/libs-team#597

@rustbot
Copy link
Collaborator

rustbot commented Jun 11, 2025

r? @joboet

rustbot has assigned @joboet.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Jun 11, 2025
@rustbot

This comment has been minimized.

Implements `trim_prefix` and `trim_suffix` methods for both `slice` and
`str` types which remove at most one occurrence of a prefix/suffix while
always returning a string/slice (rather than Option), enabling easy
method chaining.
@deven deven force-pushed the trim_prefix_suffix branch from ecbcaa2 to 32cb8f1 Compare June 11, 2025 04:29
@deven
Copy link
Author

deven commented Jun 11, 2025

r? @Amanieu

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Tracking Issue for str::trim_prefix, str::trim_suffix, slice::trim_prefix and slice::trim_suffix
4 participants