OneBite.Dev - Coding blog in a bite size

escape a string in Go

Code snippet on how to escape a string in Go

  escapedString := strings.ReplaceAll(unescapedString, `"`, `\"`)

This code uses the ReplaceAll function from the strings package in Go to escape a string. In this code, the unescapedString is a given, unescaped string. The ReplaceAll function takes two strings as arguments. The first is the string to be searched and replaced, in this case, a double quote ("). The second is the string to replace it with, in this case, a double quote preceded by a backslash (\"). This code will iterate over the unescapedString and replace all occurrences of a double quote with a backslash-followed double quote. The result of this is a new string which is the escaped version of our unescapedString, which is returned as the escapedString. The resulting escapedString is a safe string that can be used in Go without any issues.

go