From e515d80d5dfd5621a16f6fc9f08cc3c0958a8414 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Fri, 1 Feb 2013 08:41:25 -0800 Subject: bytes, strings: add TrimPrefix and TrimSuffix Everybody either gets confused and thinks this is TrimLeft/TrimRight or does this by hand which gets repetitive looking. R=rsc, kevlar CC=golang-dev https://golang.org/cl/7239044 --- src/pkg/strings/strings.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src/pkg/strings/strings.go') diff --git a/src/pkg/strings/strings.go b/src/pkg/strings/strings.go index b411ba5d8b..d4b3f03473 100644 --- a/src/pkg/strings/strings.go +++ b/src/pkg/strings/strings.go @@ -558,6 +558,24 @@ func TrimSpace(s string) string { return TrimFunc(s, unicode.IsSpace) } +// TrimPrefix returns s without the provided leading prefix string. +// If s doesn't start with prefix, s is returned unchanged. +func TrimPrefix(s, prefix string) string { + if HasPrefix(s, prefix) { + return s[len(prefix):] + } + return s +} + +// TrimSuffix returns s without the provided trailing suffix string. +// If s doesn't end with suffix, s is returned unchanged. +func TrimSuffix(s, suffix string) string { + if HasSuffix(s, suffix) { + return s[:len(s)-len(suffix)] + } + return s +} + // Replace returns a copy of the string s with the first n // non-overlapping instances of old replaced by new. // If n < 0, there is no limit on the number of replacements. -- cgit v1.3-5-g9baa