Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Retaining paragraph breaks from text

 
Ronwaldo Cruz
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm getting text from a database. It can range from simple sentences to several paragraphs. What I want to do is to retain the paragraph breaks and spaces when I display it in the JSP. Would anybody how to go about this?

Thanks.
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
execute a regex on your text which replaces \n with <br/>
 
Bauke Scholtz
Ranch Hand
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed, line breaks in HTML are to be represented by the <br> element. You can use JSTL's fn:replace for this or write a simple EL function for this like nl2br().

Do not only replace \n, it is platform dependent. Windows for instance uses \r\n. You need to replace \r\n then. Call System.getProperty("line.separator") to find out which is correct. Doing so in an EL function makes it more robust.

By the way, you do not necessarily need regex for this. It's a simple character-by-character replace, not a pattern-by-character replace. The \r and \n itself already represents the desired characters. Save yourself from the backslash-escaping headache and minor performance drop when using regex for this.
 
Ronwaldo Cruz
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.

I tried this though and I got an empty String

public static void main(String[] args) {

String separator = System.getProperty("line.separator");
System.out.println("separator: " + separator);

}

And even though I use windows I tried replacing \n and it works ok
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic