Skip to content

Golang: How to Trim Whitespace and Newlines

If you want to simply remove the leading and trailing white spaces from a string then forget about the regex and only use TrimSpace simple function from the strings package:

func strings.TrimSpace(s string) string

Code example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	myString := `  I have some leading and trailing white space  
	
	`

	fmt.Println("->", myString, "<-")

	myString = strings.TrimSpace(myString)

	fmt.Println("->", myString, "<-")
}

Leave a Reply

Your email address will not be published. Required fields are marked *