From ff5959f79ce645d7e2cb8b7866bb138c9bf1b5c1 Mon Sep 17 00:00:00 2001 From: Francisco Date: Wed, 10 Aug 2022 16:16:12 +0700 Subject: [PATCH] feature: escape quote --- string.go | 15 +++++++++++++++ string_test.go | 16 ++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/string.go b/string.go index 30cba90..0d73cb3 100644 --- a/string.go +++ b/string.go @@ -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) +} diff --git a/string_test.go b/string_test.go index 3aa38f0..08d3fba 100644 --- a/string_test.go +++ b/string_test.go @@ -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)) + } +}