How to Strip Newline Characters from a String in Golang

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Having trouble stripping newline characters from a string in Golang? The easy way I’ve found is to use strings.Replace. Also, make sure to see the “gotcha” involving runes below the example code. Sometimes you will need to change the “/n” character to the newline rune “/r/n”.

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)
}
view raw strip_newline.go hosted with ❤ by GitHub

However, beware of this gotcha involving runes. I’m still a newbie Golang coder so I don’t fully understand all of the differences between strings, bytes, runes, and characters, but sometimes the code above will not work. Instead, of stripping the newline character “/n”, you’ll need to strip the newline rune “/r/n”. In this case, your code will look something like:

string_b = strings.Replace(string_b, "\r\n", "", -1)

 

topherPedersen