aspose file tools*
The moose likes JSP and the fly likes Retaining paragraph breaks from text Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "Retaining paragraph breaks from text" Watch "Retaining paragraph breaks from text" New topic
Author

Retaining paragraph breaks from text

Ronwaldo Cruz
Ranch Hand

Joined: Oct 17, 2006
Posts: 69
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

Joined: Aug 03, 2008
Posts: 9321
    
  17

execute a regex on your text which replaces \n with <br/>


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Bauke Scholtz
Ranch Hand

Joined: Oct 08, 2006
Posts: 2458
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

Joined: Oct 17, 2006
Posts: 69
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Retaining paragraph breaks from text