6

I am not very versed in programming in general so please cut me some slack here. Is there a more elegant way to tackle this process of replacing multiple characters in a string?

strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(godiacritics.Normalize(strings.ToLower(articles[i].Name)), "-", "_"), " ", "_"), ",", "_"), ".", ""), "/", ""), "€", ""), "%", ""), "12", "halb"), "14", "viertel")

1 Answer 1

16

Create a single strings.Replacer which contains all replaceable pairs:

r := strings.NewReplacer(
    "-", "_",
    " ", "_",
    ",", "_",
    ".", "",
    "/", "",
    "€", "",
    "%", "",
    "12", "halb",
    "14", "viertel",
)

And use it like this:

s2 := r.Replace(godiacritics.Normalize(strings.ToLower(articles[i].Name)))

strings.Replacer performs all replaces in a single step (it iterates over the string once). It's also safe for concurrent use, create the Replacer onces and reuse it whenever / wherever needed.

Example code to test it:

s := "test- ,./€%:12 14"
s2 := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(s, "-", "_"), " ", "_"), ",", "_"), ".", ""), "/", ""), "€", ""), "%", ""), "12", "halb"), "14", "viertel")
fmt.Println(s2)

r := strings.NewReplacer(
    "-", "_",
    " ", "_",
    ",", "_",
    ".", "",
    "/", "",
    "€", "",
    "%", "",
    "12", "halb",
    "14", "viertel",
)

s3 := r.Replace(s)
fmt.Println(s3)

Which outputs (try it on the Go Playground):

test___:halb_viertel
test___:halb_viertel
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.