Golang : Escaping single quotes

48,448

Solution 1

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

Solution 2

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

strings.ReplaceAll(str, "'", `\'`)

Solution 3

// 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

Share:
48,448
A.D
Author by

A.D

Updated on May 31, 2021

Comments

  • A.D
    A.D almost 3 years

    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."
    
  • deepakssn
    deepakssn almost 7 years
    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 :)
  • ardnew
    ardnew over 2 years
    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