Golang: dropping single quotes

Is there a way to avoid single quotes in go?

Following:

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

Gives an error: unknown escape sequence: '

I would like str to be

"I\'m Bob, and I\'m 25."
+4
source share
2 answers

You also need to avoid the slash in the lines. Come on in.

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

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

+13
source

+ to @KeylorSanchez answer: you can wrap string replacement in reverse tick:

strings.Replace(str, "'", `\'`, -1)
+8
source

Source: https://habr.com/ru/post/1611942/


All Articles