Skip to content

Commit

Permalink
feature: escape quote
Browse files Browse the repository at this point in the history
  • Loading branch information
Francisco committed Aug 10, 2022
1 parent f6e7166 commit ff5959f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
15 changes: 15 additions & 0 deletions string.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,18 @@ func TruncateString(str string, num int) string {
}
return bnoden
}

func EscapeQuote(in string) string {
res := []byte{}
const (
doubleQuoteASCII = 34
backSlashASCII = 92
)
for i := 0; i < len(in); i++ {
if in[i] == doubleQuoteASCII && ((i > 0 && in[i-1] != backSlashASCII) || i == 0) {
res = append(res, backSlashASCII)
}
res = append(res, in[i])
}
return string(res)
}
16 changes: 16 additions & 0 deletions string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,19 @@ func Test_TruncateString(t *testing.T) {
assert.Equal(t, "Ab", TruncateString("Absolutely Longer", 2))
assert.Equal(t, "A...", TruncateString("Absolutely Longer", 4))
}

func Test_EscapeQuote(t *testing.T) {
strWithoutQuote := "this is brazil"
strWithQuote := "\"bek bek bek\""
strWithEscapedQuote := "\\\"bek\\\" bek\\\" bek\\\""

testCases := map[string]string{
strWithoutQuote: "this is brazil",
strWithQuote: "\\\"bek bek bek\\\"",
strWithEscapedQuote: "\\\"bek\\\" bek\\\" bek\\\"",
}

for in, out := range testCases {
assert.Equal(t, out, EscapeQuote(in))
}
}

0 comments on commit ff5959f

Please sign in to comment.