0

I try to escape and unescape large text using the StringEscapeUtils from Apache Commons library (v. 1.7) that will be stored and retrieved from a database, in this case a H2 database. Almost every special character is escaped and unescaped successfully except for the new line. I am using Spring Boot (v2.1.3.) with thymeleaf.

So for instance, if I try to store the following text:

 He didn't say, "Stop!"

 This is a new line!

It will store the text as:

He didn't say, \"Stop!\"\r\n\r\nThis is a new line!

Which is good. But when I unescape it with the unescapeJava method the new line character is not working correctly. I get

He didn't say, "Stop!" This is a new line!

Edit:

The unescapeJava method works when the text is displayed in a html textarea. But when it is rendered as plain html, the linebreak is not working.

EnJoY
  • 19
  • 4
  • 2
    Welcome to Stack Overflow! Please read "How to create a [mcve]". Then use the [edit] link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Dont show us some production code that is *actually* not related to your question. Step back, and create a super simple example that shows your problem. Why would we need to worry about your `addNewsItem()` method. When all you ask about is how to properly use those library methods?! So: please focus on the real core of your question, and remove anything that doesnt matter. – GhostCat Sep 03 '19 at 07:24
  • This should work. Show the example code that has this problem, please. – Adder Sep 03 '19 at 07:53
  • Can you try \\n instead of \n. – Isuri Subasinghe Sep 03 '19 at 07:57
  • @IMS already tried that one, but it will display as \n. I edited my question btw – EnJoY Sep 03 '19 at 08:03

2 Answers2

2

The unescapeJava method works when the text is displayed in a html textarea. But when it is rendered as plain html, the linebreak is not working.

Please check your HTML source, it most likely is there

In HTML a newline in source does not introduce a newline on screen, if you want that you should replace newlines with for example <br/> tags.

See more at:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br

  • You're right, forgot to mention that before. The newline is actually rendered in my HTML source. But I think I already found a solution to this problem. In CSS I used white-space: pre-wrap that will preserve white lines and new line characters. – EnJoY Sep 03 '19 at 08:21
1

What @Martin van Wingerden says is correct. A newline in source does not introduce / render it on screen. I found this thread

Render a string in HTML and preserve spaces and linebreaks

which explains that you can use CSS white-space: pre-wrap that will preserve white spaces and line breaks in formatting.

EnJoY
  • 19
  • 4