golang:如何将”\n”替换为”

huangapple go评论87阅读模式
英文:

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

问题

我试过使用strings.Replace(s,"\n","<br>",-1);来做这个。但是结果是不同的,它在网页浏览器中显示为<br>,但实际上不是"<br>"。有人可以告诉我如何做到这一点吗?

我的主要目标是将<textarea>中的换行符更改为html中的<br>标签。

任何线索都将受到欢迎,提前感谢。

PS:

问:你是想从数据库中获取它吗?

答:是的,我从GAE的数据库中获取字符串,然后用<br>替换\n。从数据库中获取的字符串有什么不同吗?

英文:

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

My primary goal is to change the end of line character from a &lt;textarea&gt; into a &lt;br&gt; 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 &lt;br&gt;. Is there anything different with string from database?

答案1

得分: 16

你的代码中其他地方可能存在问题 - 可能是在将输出放入模板时进行了转义?你发布的代码行将换行符替换为br,并且是正确的 - 可以参考这个简单的测试:

package main
import("strings")

func main() {
    s := "我是一个包含换行符的字符串\n"
    s = strings.Replace(s,"\n","<br>",-1)
    println(s)
}

你需要发布更多的代码,以便其他人可以找到你出错的地方,例如发布创建/操作字符串的函数以及输出到HTML的模板部分。

在Go playground上查看 - http://play.golang.org/p/KMzxku4UtL

英文:

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(&quot;strings&quot;)

func main() {
	s := &quot;I am a string\nContaining new lines&quot;
	s = strings.Replace(s,&quot;\n&quot;,&quot;&lt;br&gt;&quot;,-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

答案2

得分: 2

问题已解决。

问题出在模板文件中。我使用了 |html 来转义内容。当我在代码中移除了 "|html",一切都正常了。

感谢大家的帮助。

英文:

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.

huangapple
  • 本文由 发表于 2012年10月1日 18:40:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/12671713.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定