Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang : Escaping single quotes

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."
like image 360
A.D Avatar asked Oct 16 '15 12:10

A.D


People also ask

How do you escape a single quote?

Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.

How do I remove single quotes from a string in Golang?

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.

How do you escape a single quote from a string?

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(\).

How do you escape characters in Golang?

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.


3 Answers

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

like image 88
syyongx Avatar answered Oct 24 '22 03:10

syyongx


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

strings.ReplaceAll(str, "'", `\'`)
like image 30
coquin Avatar answered Oct 24 '22 04:10

coquin


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

like image 32
KeylorSanchez Avatar answered Oct 24 '22 02:10

KeylorSanchez