Skip to content

Instantly share code, notes, and snippets.

Created February 3, 2020 20:56
What would you like to do?
How to Strip Newline Characters from a String in Golang
package main
import (
func main() {
var string_a string = "My super \nsweet \nstring has \nmany newline\n characters"
var string_b string = string_a
string_b = strings.Replace(string_b, "\n", "", -1)
Copy link

twocs commented Mar 6, 2021

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

Copy link

samiam2013 commented May 27, 2022

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.

Copy link

daluu commented Jun 4, 2022

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.

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