Sunday, November 22, 2009

Converting UTF-8 characters to HTML entities in Java

This function takes string as input and converts all special characters to its equivalent HTML entity code and returns newly built string.

HTML entity code conversion is done by extracting Unicode bits from character and combining it to build integer value which will be then combined with “&#” and “;” that is “&#” + integer value + “;”

Example:

Input string:

日本について - Japan

Output string:

日本について - Japan

Primary usage:

If you have a web page in which content type of the page is set to other than UTF-8 and if you want to display any UTF-8 characters in that page those characters not displayed properly. To solve this, you can convert those UTF-8 characters to HTML entity codes using this function and display it as the content type of page will have no effect on these HTML Entity codes.

Code:
public static String buildHtmlEntityCode(String input) {
StringBuffer output = new StringBuffer(input.length() * 2);

int len = input.length();
int code,code1,code2,code3,code4;
char ch;

for( int i=0; i<len; ) {
code1 = input.codePointAt(i);
if( code1 >> 3 == 30 ){
code2 = input.codePointAt(i + 1);
code3 = input.codePointAt(i + 2);
code4 = input.codePointAt(i + 3);
code = ((code1 & 7) << 18) | ((code2 & 63) << 12) | ((code3 & 63) << 6) | ( code4 & 63 );
i += 4;
output.append("&#" + code + ";");
}
else if( code1 >> 4 == 14 ){
code2 = input.codePointAt(i + 1);
code3 = input.codePointAt(i + 2);
code = ((code1 & 15) << 12) | ((code2 & 63) << 6) | ( code3 & 63 );
i += 3;
output.append("&#" + code + ";");
}
else if( code1 >> 5 == 6 ){
code2 = input.codePointAt(i + 1);
code = ((code1 & 31) << 6) | ( code2 & 63 );
i += 2;
output.append("&#" + code + ";");
}
else {
code = code1;
i += 1;

ch = (char)code;
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') {
output.append(ch);
}
else {
output.append("&#" + code + ";");
}
}
}

return output.toString();
}