For example, I have a string, consists of "sample.zip". How do I remove the ".zip" extension using strings package or other else?
8 Answers
Try:
basename := "hello.blah"
name := strings.TrimSuffix(basename, filepath.Ext(basename))
TrimSuffix basically tells it to strip off the trailing string which is the extension with a dot.
-
17Note that
filepath.Ext("test.tar.gz")
returns.gz
which may or may not be what you want. Commented Oct 4, 2016 at 18:30 -
1If you want the filename in case of multiple extensions (e.g.
tar.gz
) usestrings.Split
with dot separator play.golang.com/p/nyhC6-YJ7PE Commented Dec 13, 2019 at 13:53 -
Ext
is non reliable method, it also includes parameter. givenhello.blah?foo=bar
, it would return.blah?foo=bar
Commented Aug 8, 2020 at 16:31 -
3@TomSawyer You should always use the
net/url
package to parse your URL before doing anything with the path. You likely also want to usepath.Ext
rather thanfilepath.Ext
, as it's a path received over HTTP rather than one designed for use with the filesystem.– squirlCommented Nov 4, 2020 at 23:25 -
1The answer by Paul Ruane avoids an unnecessary string comparison in strings.TrimSuffix. Commented May 22, 2021 at 5:26
Edit: Go has moved on. Please see Keith's answer.
Use path/filepath.Ext to get the extension. You can then use the length of the extension to retrieve the substring minus the extension.
var filename = "hello.blah"
var extension = filepath.Ext(filename)
var name = filename[0:len(filename)-len(extension)]
Alternatively you could use strings.LastIndex to find the last period (.) but this may be a little more fragile in that there will be edge cases (e.g. no extension) that filepath.Ext
handles that you may need to code for explicitly, or if Go were to be run on a theoretical O/S that uses a extension delimiter other than the period.
-
strings.TrimSuffix, underneath, does the same array math/indices :) Commented May 29, 2014 at 6:58
-
2@rogerdpack, yes people should use Keith's answer.
TrimSuffix
didn't exist in Go when I wrote this answer (it was added in Go 1.1 in February 2013). Commented Oct 15, 2014 at 10:06 -
filepath.Ext(filename)
did not work for me, I needed to usepath.Ext(filename)
instead. Thanks tho. Commented Apr 2, 2019 at 13:04 -
2
strings.TrimSuffix
would make an unnecessary/redundant comparison compared to pure string slicing. Not a big deal in terms of performance but there is a tiny difference and both solutions are easy to understand. Commented Mar 12, 2020 at 14:21
This is just one line more performant. Here it is:
filename := strings.Split(file.Filename, ".")[0]
This way works too:
var filename = "hello.blah"
var extension = filepath.Ext(filename)
var name = TrimRight(filename, extension)
but maybe Paul Ruane's method is more efficient?
-
7I think TrimRight here removes a "cutset" (i.e. character set) from the end, which may not be what you want here: golang.org/pkg/strings/#TrimRight (see also TrimSuffix) Commented May 29, 2014 at 6:55
I am using go1.14.1, filepath.Ext
did not work for me, path.Ext
works fine for me
var fileName = "hello.go"
fileExtension := path.Ext(fileName)
n := strings.LastIndex(fileName, fileExtension)
fmt.Println(fileName[:n])
Playground: https://play.golang.org/p/md3wAq_obNc
Documnetation: https://golang.org/pkg/path/#Ext
Here is example that does not require path
or path/filepath
:
func BaseName(s string) string {
n := strings.LastIndexByte(s, '.')
if n == -1 { return s }
return s[:n]
}
and it seems to be faster than TrimSuffix
as well:
PS C:\> go test -bench .
goos: windows
goarch: amd64
BenchmarkTrimFile-12 166413693 7.25 ns/op
BenchmarkTrimPath-12 182020058 6.56 ns/op
BenchmarkLast-12 367962712 3.28 ns/op
I've been using this:
name, _, _ := strings.Cut(fullName, ".")
It returns anything up to the first dot, or the whole string if there ain't no dot.
Starting from Go 1.23, there is now iter, so it's possible to filter strings.
fmt.Println(string(slices.Collect(func(yield func(E rune) bool) {
for _, c := range "abc.tar.gz" {
if c == '.' {
return
}
yield(c)
}
}))) // abc
Although it's not more concise, it might be helpful in special filtering situations, for example:
// username_algorithm.pub => username
// username.pub => username
fmt.Println(string(slices.Collect(func(yield func(rune) bool) {
s := "username_rsa.pub"
for _, r := range filepath.Base(s) {
if r == '.' || r == '_' {
return
}
yield(r)
}
}))) // username