Grzenio
Grzenio

Reputation: 36679

Encoding strings into HTML in Java

I need to encode a Java String to display properly as part of an HTML document, e.g. all new lines or tab characters. So I have e.g. "one\ntwo", and I want to get something like "one<br>two". Do you know any library that would do it for me?

Upvotes: 1

Views: 7662

Answers (3)

Ben
Ben

Reputation: 472

try using preformat tag <pre>

Upvotes: 3

Adamski
Adamski

Reputation: 54725

Spring Framework's HtmlUtils.htmlEscape(String) method should do the trick:

Turn special characters into HTML character references. Handles complete character set defined in HTML 4.01 recommendation.

Upvotes: 2

Martin Wickman
Martin Wickman

Reputation: 19925

You don't need a library for those simple cases. A simple loop over string.replaceAll() should do the trick.

If you are looking for more fancy conversions (such as done here on SO or in a wiki) you can check out the Java Wikipedia API. Code example here. Although I guess it may be a bit overkill for your needs.

Upvotes: 1

Related Questions