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."
Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.
In your go source files, if you try to use single quotes for a multi-character string literal, you'll get a compiler error similar to illegal rune literal . What you can do instead for removing quotes from the start and end of a string, is use the strings. Trim function to take care of it.
You need to escape single quote when the literal is enclosed in single code using the backslash(\) or need to escape double quotes when the literal is enclosed in a double code using a backslash(\).
To insert escape characters, use interpreted string literals delimited by double quotes. The escape character \t denotes a horizontal tab and \n is a line feed or newline.
// 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
+to @KeylorSanchez answer: your can wrap replace string in back-ticks:
strings.ReplaceAll(str, "'", `\'`)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With