Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Trim line - remove trailing newline from string

  • trim
  • TrimSuffix
package main

import (
	"fmt"
	"strings"
)

func main() {
	line := "hello\n"
	line = strings.TrimSuffix(line, "\n") // remove newline
	fmt.Printf("'%s'\n", line)

	line = strings.TrimSuffix(line, "\n") // not bothered if there was no newline
	fmt.Printf("'%s'\n", line)

	line = "hello\n\n"
	line = strings.TrimSuffix(line, "\n") // removing only one newline
	fmt.Printf("'%s'\n", line)
}
'hello'
'hello'
'hello
'