Golang : Escaping single quotes

A.D picture A.D · Oct 16, 2015 · Viewed 43.3k times · Source

Is there a way to escape single quotes in go?

The following:

str := "I'm Bob, and I'm 25."
str = strings.Replace(str, "'", "\'", -1)

Gives the error: unknown escape sequence: '

I would like str to be

"I\'m Bob, and I\'m 25."

Answer

KeylorSanchez picture KeylorSanchez · Oct 16, 2015

You need to ALSO escape the slash in strings.Replace.

str := "I'm Bob, and I'm 25."
str = strings.Replace(str, "'", "\\'", -1)

https://play.golang.org/p/mZaaNU3FHw