How to Strip Newline Characters from a String in Golang

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 (
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)
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)