That's a simple strings.Replace()
call:
text = strings.Replace(text, "
", "
", -1)
Output before and after the replace (try it on the Go Playground):
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua.
Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua.
Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Note that this will still leave newline character at the beginning and at the end of your text. If you also want to get rid of them, you may use strings.Trim()
:
text = strings.Replace(text, "
", "
", -1)
text = strings.Trim(text, "
")
Note: strings.TrimSpace()
would come first to mind, but it's not a good choice as that would also remove the indentation from the first line (" Lorem"
) which is unwanted. We really just want to get rid of extra prefix and postfix newlines.
To verify the difference:
text = strings.Replace(text, "
", "
", -1)
fmt.Printf("%q
", text)
text = strings.Trim(text, "
")
fmt.Printf("%q
", text)
Output:
"
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua.
Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
"
" Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua.
Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat."
To wrap it in a helper function:
func unindent(s string, spaces int) string {
old := "
" + strings.Repeat(" ", spaces)
s = strings.Replace(s, old, "
", -1)
return strings.Trim(s, "
")
}
And using it:
text = unindent(text, 8)
An alternative way to create the old
replaceable string:
func unindent(s string, spaces int) string {
old := fmt.Sprintf("%*c", -spaces-1, '
')
s = strings.Replace(s, old, "
", -1)
return strings.Trim(s, "
")
}