[Golang] Replace Space and Newline in String


Use Go regexp package to repace spaces and newline in the string with only one space.

Problem

We have a string as follows:

`CONDUIT
                FITTINGS`

There are spaces and newline in the string. We want the string to become

`CONDUIT FITTINGS`

How to do it?

Solution

Run Code on Go Playground

package main

import (
      "fmt"
      "regexp"
)

var str = `CONDUIT
                FITTINGS`

func TrimSpaceNewlineInString(s string) string {
      re := regexp.MustCompile(` +\r?\n +`)
      return re.ReplaceAllString(s, " ")
}

func main() {
      fmt.Println(str)
      fmt.Println(TrimSpaceNewlineInString(str))
}

Trick: If you are not sure whether the regular expression is written correctly, use [2] to test it online first.

Output

CONDUIT
                FITTINGS
CONDUIT FITTINGS

Tested on: Go Playground


References:

[1]Golang: Issues replacing newlines in a string from a text file - Stack Overflow
[2]Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript