Reputation: 63
I want to remove the last 4 characters from a string, so "test.txt" becomes "test".
package main
import (
"fmt"
"strings"
)
func main() {
file := "test.txt"
fmt.Print(strings.TrimSuffix(file, "."))
}
Upvotes: 4
Views: 5190
Reputation: 3779
Though there is already an accepted answer, I want to share some slice tricks for string manipulation.
Remove last n characters from a string
As the title says, remove the last 4 characters from a string
, it is very common usage of slices
, ie,
file := "test.txt"
fmt.Println(file[:len(file)-4]) // you can replace 4 with any n
Output:
test
Playground example.
Remove file extensions:
From your problem description, it looks like you are trying to trim the file extension suffix (ie, .txt
) from the string.
For this, I would prefer @colminator's answer from above, which is
file := "test.txt"
fmt.Println(strings.TrimSuffix(file, filepath.Ext(file)))
Upvotes: 4
Reputation: 1877
You can use this to remove everything after last "."
go playground
package main
import (
"fmt"
"strings"
)
func main() {
sampleInput := []string{
"/www/main.js",
"/tmp/test.txt",
"/tmp/test2.text",
"/tmp/test3.verylongext",
"/user/bob.smith/has.many.dots.exe",
"/tmp/zeroext.",
"/tmp/noext",
"",
"tldr",
}
for _, str := range sampleInput {
fmt.Println(removeExtn(str))
}
}
func removeExtn(input string) string {
if len(input) > 0 {
if i := strings.LastIndex(input, "."); i > 0 {
input = input[:i]
}
}
return input
}
Upvotes: 0
Reputation: 22037
This will safely remove any dot-extension - and will be tolerant if no extension is found:
func removeExtension(fpath string) string {
ext := filepath.Ext(fpath)
return strings.TrimSuffix(fpath, ext)
}
Playground example.
Table tests:
/www/main.js -> '/www/main'
/tmp/test.txt -> '/tmp/test'
/tmp/test2.text -> '/tmp/test2'
/tmp/test3.verylongext -> '/tmp/test3'
/user/bob.smith/has.many.dots.exe -> '/user/bob.smith/has.many.dots'
/tmp/zeroext. -> '/tmp/zeroext'
/tmp/noext -> '/tmp/noext'
-> ''
Upvotes: 5