Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode special chars in html content

Tags:

java

html

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:    &lt;&gt;&amp;abcdef&copy;
like image 428
Roshan Avatar asked Apr 21 '11 08:04

Roshan


4 Answers

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.

like image 95
das_weezul Avatar answered Oct 26 '22 06:10

das_weezul


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.

like image 22
Ulilop Avatar answered Oct 26 '22 07:10

Ulilop


Convert

< → &lt;

> → &gt;

' → &#39;

" → &quot;

& → &amp;

Source of knowledge: https://www.php.net/manual/en/function.htmlspecialchars.php

like image 3
Notinlist Avatar answered Oct 26 '22 06:10

Notinlist


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

like image 2
ezmilhouse Avatar answered Oct 26 '22 06:10

ezmilhouse