Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing \n with <br> tags

I have some user provided text which I'd like to display correctly in browser (with new lines replaced with <br/>-tags). I wish to have every other HTML tag escaped. What's the best way to do this?

like image 236
szymond Avatar asked Nov 04 '13 11:11

szymond


1 Answers

Not the prettiest solution, but this will work. If the view accepts a string parameter str, then @Html(HtmlFormat.escape(str).toString.replace("\n", "<br />")) will first escape the string, then replace all instances of \n with <br />, and lastly transform it back to html so that Play doesn't try to escape already escaped characters. If you want to also escape \r or \r\n you could chain another replace onto that, or use a regex instead.

like image 162
Michael Zajac Avatar answered Oct 22 '22 09:10

Michael Zajac