Cookies management by TermsFeed Cookie Consent

👯 Remove duplicate spaces from a string in Go

introduction strings regex

To remove duplicate whitespaces from a string in Go, use strings.Fields() function that splits the string around one or more whitespace characters, then join the slice of substrings using strings.Join() with a single space separator. Alternatively, you can use a regular expression to find duplicate whitespace characters and replace them using the ReplaceAllString() method from the regexp package.

Remove duplicate whitespaces using strings.Fields() function

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "GOSAMPLES.dev is  \t \r\n the best Golang \t\t\t\t    website in the \n world!"

    res := strings.Join(strings.Fields(s), " ")
    fmt.Println(res)
}

In this method, we do two things:

[]string{"GOSAMPLES.dev", "is", "the", "best", "Golang", "website", "in", "the", "world!"}

Remove duplicate whitespaces using regular expressions

package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := "GOSAMPLES.dev is  \t \r\n the best Golang \t\t\t\t    website in the \n world!"

    pattern := regexp.MustCompile(`\s+`)
    res := pattern.ReplaceAllString(s, " ")
    fmt.Println(res)
}

Using regular expressions, we can achieve the same effect as in the previous method. We define \s+ pattern that matches at least one whitespace character ([ \t\r\n\f]) and then replace all occurrences of that expression with a single space, obtaining the string with duplicate whitespaces removed.


Both methods produce the same result, which is:

GOSAMPLES.dev is the best Golang website in the world!

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🍒 Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🔟 Convert string to bool in Go

Learn how to parse a string as a bool
introduction strings bool