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."
You need to ALSO escape the slash in strings.Replace.
str := "I'm Bob, and I'm 25."
str = strings.ReplaceAll(str, "'", "\\'")
+to @KeylorSanchez answer: your can wrap replace string in back-ticks:
strings.ReplaceAll(str, "'", `\'`)
// 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
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)