14

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."
A.D
  • 2,150
  • 3
  • 13
  • 19

4 Answers4

33

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

a8m
  • 9,334
  • 4
  • 37
  • 40
KeylorSanchez
  • 1,320
  • 9
  • 15
13

+to @KeylorSanchez answer: your can wrap replace string in back-ticks:

strings.ReplaceAll(str, "'", `\'`)
a8m
  • 9,334
  • 4
  • 37
  • 40
coquin
  • 1,338
  • 1
  • 13
  • 22
  • 1
    Even the first string can be in backquote. In my case i had to replace \" with " in my dbjson variable dbjson = strings.Replace(dbjson, \`\"\`, \`"\`, -1) This answer helped me to get there :) – deepakssn May 21 '17 at 05:53
1
// addslashes()
func Addslashes(str string) string {
    var buf bytes.Buffer
    for _, char := range str {
        switch char {
        case '\'':
            buf.WriteRune('\\')
        }
        buf.WriteRune(char)
    }
    return buf.String()
}

If you want to escaping single/double quotes or backlash, you can refer to https://github.com/syyongx/php2go

syyongx
  • 21
  • 2
  • Probably best to use `var buf strings.Builder` (instead of `bytes.Buffer`) in this case. It has the same methods, so no other changes needed – ardnew Jan 19 '22 at 19:15
0

strings.Replacer can be used to escape a number of different characters at once. Also handy if you want to reuse the same logic in different places.

quoteEscaper := strings.NewReplacer(`'`, `\'`, `"`, `\"`)
str := `They call me "Bob", and I'm 25.`
str = quoteEscaper.Replace(str)

https://go.dev/play/p/6IFecrHmN3z

acorello
  • 4,473
  • 4
  • 31
  • 46