Trim string's suffix or extension?

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.

strings#TrimSuffix


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.


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?


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

https://golang.org/pkg/strings#LastIndexByte