Search code examples
goescapingbackslashquote

Golang : Escaping single quotes


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."

Solution

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

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

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