Skip to main content
  1. Tutorials/

👯 Remove duplicate spaces from a string in Go

·2 mins

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:

  • We split the string around one or more whitespace characters using the strings.Fields() function. The whitespace characters are defined by unicode.IsSpace(), and include '\t', '\n', '\r', ' ', among others. As a result, we get the slice:
[]string{"GOSAMPLES.dev", "is", "the", "best", "Golang", "website", "in", "the", "world!"}
  • We join the slice of substrings using the strings.Join() function with a single space " " as a separator. This way, we construct the result string with all duplicate whitespaces removed.

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!