Use the strings.TrimSpace() function to remove leading and trailing whitespace, or strings.Trim() with a custom cutset for specific characters. These functions are part of the standard strings package and return a new string without modifying the original.
Here is the standard approach for removing common whitespace characters (spaces, tabs, newlines, carriage returns):
package main
import (
"fmt"
"strings"
)
func main() {
input := " hello world \n"
// Removes leading and trailing whitespace
cleaned := strings.TrimSpace(input)
fmt.Printf("Original: %q\n", input)
fmt.Printf("Trimmed: %q\n", cleaned)
// Output:
// Original: " hello world \n"
// Trimmed: "hello world"
}
If you need to remove only specific characters (e.g., spaces but not newlines) or trim from just one side, use strings.Trim(), strings.TrimLeft(), or strings.TrimRight(). These accept a cutset string containing every character you want to remove.
package main
import (
"fmt"
"strings"
)
func main() {
input := "###hello###"
// Removes '#' from both ends
cleaned := strings.Trim(input, "#")
// Removes only leading spaces
leftTrimmed := strings.TrimLeft(" test", " ")
// Removes only trailing newlines
rightTrimmed := strings.TrimRight("test\n\n", "\n")
fmt.Printf("%q\n", cleaned) // "hello"
fmt.Printf("%q\n", leftTrimmed) // "test"
fmt.Printf("%q\n", rightTrimmed) // "test"
}
Note that TrimSpace is generally preferred for user input or log parsing because it handles all Unicode whitespace characters defined by the Unicode standard, whereas Trim with a manual cutset only removes the exact characters you specify. If you need to trim whitespace from the middle of a string, these functions won't work; you would need to split the string by whitespace and join it back together using strings.Join(strings.Fields(input), " ").