How to Trim “[” char from a string in Golang

You are missing reading the doc. strings.Trim():

func Trim(s string, cutset string) string

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

The [ character in your input is not in a leading nor in a trailing position, it is in the middle, so strings.Trim() – being well behavior – will not remove it.

Try strings.Replace() instead:

s := "this[things]I would like to remove"
t := strings.Replace(s, "[", "", -1)
fmt.Printf("%s\n", t)   

Output (try it on the Go Playground):

thisthings]I would like to remove

There is also a strings.ReplaceAll() added in Go 1.12 (which is basically a “shorthand” for Replace(s, old, new, -1)).

Leave a Comment