user1445967
user1445967

Reputation: 1570

jsoup / Java - how to append a nonbreaking space

Calling [Element].appendtext(" ") causes the ampersand to be escaped and so the user sees the ampersand on the rendered HTML page. I don't want the page to render the HTML code.

I actually do want the html page to render whitespace.

Upvotes: 0

Views: 1597

Answers (2)

Michael Gantman
Michael Gantman

Reputation: 7792

There is an open-source library called MgntUtils that has a feature that takes a regular String and creates a String for Html format where the String formatting will be preserved. I.e. all the spaces in the String will be replaced with non-breaking spaces and all the new lines will be replaced with 'br' tags. The advantage that if you just print your String as text non-braking spaces will look just like regular space and not as "\u00A0" or nbsp escape. You will, of course, see br tags, but still, your String will look by far more readable. Here is JavaDoc for the method. I found it sometimes very convenient. The code would just look

String htmlFormattedStr = formatStringToPreserveIndentationForHtml(rawText);

The library Maven artifacts could be found here and the library itself as a Jar file as well as source code and JavaDoc can be found on Github. Here is the link to the article about the library

Upvotes: 0

kaya3
kaya3

Reputation: 51034

A non-breaking space can be written into a string literal using a Unicode escape sequence: "\u00A0".

However, if you want all whitespace within an element to be rendered literally, consider using normal spaces but applying a CSS property such as white-space: pre;.

Upvotes: 2

Related Questions