How to remove quotes from around a string in Golang
Use a slice expression:
s = s[1 : len(s)-1]
If there's a possibility that the quotes are not present, then use this:
if len(s) > 0 && s[0] == '"' {
s = s[1:]
}
if len(s) > 0 && s[len(s)-1] == '"' {
s = s[:len(s)-1]
}
playground example
Use slice expressions. You should write robust code that provides correct output for imperfect input. For example,
package main
import "fmt"
func trimQuotes(s string) string {
if len(s) >= 2 {
if s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1]
}
}
return s
}
func main() {
tests := []string{
`"hello""world"`,
`"""hello"""`,
`"`,
`""`,
`"""`,
`goodbye"`,
`"goodbye"`,
`goodbye"`,
`good"bye`,
}
for _, test := range tests {
fmt.Printf("`%s` -> `%s`\n", test, trimQuotes(test))
}
}
Output:
`"hello""world"` -> `hello""world`
`"""hello"""` -> `""hello""`
`"` -> `"`
`""` -> ``
`"""` -> `"`
`goodbye"` -> `goodbye"`
`"goodbye"` -> `goodbye`
`goodbye"` -> `goodbye"`
`good"bye` -> `good"bye`
strings.Trim()
can be used to remove the leading and trailing whitespace from a string. It won't work if the double quotes are in between the string.
// strings.Trim() will remove all the occurrences from the left and right
s := `"""hello"""`
fmt.Println("Before Trim: " + s) // Before Trim: """hello"""
fmt.Println("After Trim: " + strings.Trim(s, "\"")) // After Trim: hello
// strings.Trim() will not remove any occurrences from inside the actual string
s2 := `""Hello" " " "World""`
fmt.Println("\nBefore Trim: " + s2) // Before Trim: ""Hello" " " "World""
fmt.Println("After Trim: " + strings.Trim(s2, "\"")) // After Trim: Hello" " " "World
Playground link - https://go.dev/play/p/yLdrWH-1jCE