In Java, Is there a third party source available or quick command to convert html special chars in a string to html encoded content?
For example:
Original code: <>&abcdef ©
After encoding: <>&abcdef©
If you want to convert a string to HTML entities to test something quickly, you can use webservices like this one:
http://www.primitivetype.com/resources/htmlentities.php
[EDIT] For Java you can use the StringEscapeUtils from Apache Commons Lang. See this thread: Recommended method for escaping HTML in Java
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
// ...
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = escapeHtml(source);
I borrowed the example from the thread mentioned above.
This is old, but it doesn't have an accepted answer yet. This is my version with pure java:
public String toHTML(String str) {
String out = "";
for (char c: str.toCharArray()) {
if(!Character.isLetterOrDigit(c))
out += String.format("&#x%x;", (int)c);
else
out += String.format("%s", c);
}
return out;
}
Works great with html5 and utf-8.
Convert
< → <
> → >
' → '
" → "
& → &
Source of knowledge: https://www.php.net/manual/en/function.htmlspecialchars.php
Javascript Solution: Find working fiddle here: http://jsfiddle.net/ezmilhouse/Zb5C9/1/
===
Sample uses 2 functions borrowed from php.js:
get_html_translation_table()
https://github.com/kvz/phpjs/raw/master/functions/strings/get_html_translation_table.js
htmlentities()
https://github.com/kvz/phpjs/raw/master/functions/strings/htmlentities.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With