Quick actions

cmd+k|ctrl+k

Navigation

Languages

Strings / Normalize newlines / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-03-26T09:39:26Z

Updated

2019-03-26T09:39:26Z

package main

import (
	"bytes"
	"fmt"
)

// NormalizeNewlines normalizes \r\n (windows) and \r (mac)
// into \n (unix)
func NormalizeNewlines(d []byte) []byte {
	// replace CR LF \r\n (windows) with LF \n (unix)
	d = bytes.Replace(d, []byte{13, 10}, []byte{10}, -1)
	// replace CF \r (mac) with LF \n (unix)
	d = bytes.Replace(d, []byte{13}, []byte{10}, -1)
	return d
}

func main() {
	d := []byte("new\r\nline")
	d = NormalizeNewlines(d)
	fmt.Printf("%#v\n", string(d))
}
INFO