@Optional String charset)
{
if (string.length() == 0)
return env.getEmptyString();
ArrayValue htmlEntities = null;
boolean isUnicode = env.isUnicodeSemantics();
if (isUnicode) {
if (HTML_ENTITIES_ARRAY_UNICODE_ENTITY_KEY == null)
HTML_ENTITIES_ARRAY_UNICODE_ENTITY_KEY = toUnicodeArray(env, HTML_ENTITIES_ARRAY_ENTITY_KEY);
htmlEntities = HTML_ENTITIES_ARRAY_UNICODE_ENTITY_KEY;
}
else
htmlEntities = HTML_ENTITIES_ARRAY_ENTITY_KEY;
EncodingWriter out = null;
if (! isUnicode) {
if (charset == null || charset.length() == 0)
charset = env.getRuntimeEncoding();
out = Encoding.getWriteEncoding(charset);
}
int len = string.length();
int htmlEntityStart = -1;
StringValue result = env.createStringBuilder();
try {
// Loop through each character
for (int i = 0; i < len; i++) {
char ch = string.charAt(i);
// Check whether it's a html entity i.e. starts with '&' and ends with ';'
if (ch == '&' && htmlEntityStart < 0) {
htmlEntityStart = i;
}
else if (htmlEntityStart < 0) {
// else add it to result.
result.append(ch);
}
else if (ch == ';') {
// If so substitute the entity and add it to result.
StringValue entity = string.substring(htmlEntityStart, i + 1);
Value value = htmlEntities.get(entity);
if (value.isNull()) {
result.append(entity);
}
else if (isUnicode) {