Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim string's suffix or extension?

Tags:

string

go

For example, I have a string, consists of "sample.zip". How do I remove the ".zip" extension using strings package or other else?

like image 567
Coder Avatar asked Oct 23 '12 09:10

Coder


People also ask

How do I trim a string in Golang?

1. Trim: This function is used to trim the string all the leading and trailing Unicode code points which are specified in this function. Here, str represent the current string and cutstr represents the elements which you want to trim in the given string. str1 := "!!

Does Golang have a prefix?

In Golang strings, you can check whether the string begins with the specified prefix or not with the help of HasPrefix() function. This function returns true if the given string starts with the specified prefix and return false if the given string does not start with the specified prefix.


2 Answers

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.

like image 25
Paul Ruane Avatar answered Oct 13 '22 06:10

Paul Ruane


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

like image 195
Keith Cascio Avatar answered Oct 13 '22 06:10

Keith Cascio