Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang: how to replace "\n" with "<br>"

Tags:

html

replace

go

I tried to do it using strings.Replace(s,"\n","<br>",-1); But the result is something different which could be displayed as <br> in a web browser but is in fact not "<br>". Can anyone tell me how to do this?

My primary goal is to change the end of line character from a <textarea> into a <br> tag in html.

Any clue would be welcome, thanks in advance.

PS:

Q: Are you trying to get it from database?

A: Yeah, I get the string from GAE's database, and then replace \n with <br>. Is there anything different with string from database?

like image 242
DeanSinaean Avatar asked Oct 01 '12 10:10

DeanSinaean


2 Answers

There is a problem elsewhere in your code - perhaps the output is being escaped when put into a template? The line you have posted will replace newlines with br and is correct - see this simple test:

package main
import("strings")

func main() {
    s := "I am a string\nContaining new lines"
    s = strings.Replace(s,"\n","<br>",-1)
    println(s)
}

You'd need to post more code than this for people to find where you are going wrong, for example post the function which creates/manipulates the string, and the bit of template where it is output to html.

On Go playground - http://play.golang.org/p/KMzxku4UtL

like image 92
Kenny Grant Avatar answered Nov 14 '22 10:11

Kenny Grant


https://stackoverflow.com/users/296559/robotamer got it right. Problem solved.

The problem is in the template file. I used |html to escape the contents. When I removed "|html" in the code, everything is fine.

Thank you all for your help.

like image 2
DeanSinaean Avatar answered Nov 14 '22 09:11

DeanSinaean