Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created February 3, 2020 20:56
Show Gist options
  • Select an option

  • Save topherPedersen/a6d1f4f9a9e95852a3d1907b4e505625 to your computer and use it in GitHub Desktop.

Select an option

Save topherPedersen/a6d1f4f9a9e95852a3d1907b4e505625 to your computer and use it in GitHub Desktop.
How to Strip Newline Characters from a String in Golang
package main
import (
"fmt"
"strings"
)
func main() {
var string_a string = "My super \nsweet \nstring has \nmany newline\n characters"
fmt.Println(string_a)
var string_b string = string_a
string_b = strings.Replace(string_b, "\n", "", -1)
fmt.Println(string_b)
}
@twocs

twocs commented Mar 6, 2021

Copy link
Copy Markdown

Equally:
strings.ReplaceAll(string_b, "\n", "")

@samiam2013

samiam2013 commented May 27, 2022 •

Copy link
Copy Markdown

if you're looking to remove padding from the end of your string there's strings.TrimRight(string_b, "\r\n") where each character in that list will be removed.

also, super nitpicky but the convention for variables in Go is camelCase not snake_case.

@daluu

daluu commented Jun 4, 2022

Copy link
Copy Markdown

There's also strings.TrimSuffix(string_b, "\r\n").

In my case tough, can't seem to trim the newline at the end of command output from cat on a file.

@moo-im-a-cow

Copy link
Copy Markdown

@daluu

In my case tough, can't seem to trim the newline at the end of command output from cat on a file.

TrimSuffix requires all characters in the correct order to be present.
if the file only has \n, then \r\n wont be trimmed because those 2 characters dont exist

files will contain only \n if they're created on linux or macos or wsl
they will have both \r\n characters if they're created on windows

what you want is strings.TrimRight(string_b, "\r\n"), it removes any individual character from the end of the string.
if there is just \n, it removes it, and if there's \r\n it removes both

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment