3

I have a requirement to remove HTML special characters and replace the special character with the respective value in a string.

For example:

I have a string like this:

String text="Federation of AP Chambers of Commerce & Industry Awards for the year 2010-11. Speaking on the occasion, 
He said, "About 54 percent of the population is youth aged below 25 years. We have to use their energy and 
intelligence for development of the state as well as the country.The youth trained will also be absorbed by 
companies.’"

" needs to be replaced with " and & needs to be replaced with & and ’ needs to be replaced with .

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
String
  • 3,660
  • 10
  • 43
  • 66

2 Answers2

4

You can't have any specific method from API to do this. Use the below method.

String text="Federation of AP Chambers of Commerce & Industry Awards for the year 2010-11. Speaking on the occasion, 
He said, "About 54 percent of the population is youth aged below 25 years. We have to use their energy and 
intelligence for development of the state as well as the country.The youth trained will also be absorbed by 
companies.’&quot";

    text= replaceAll(text,""","\"");

    text= replaceAll(text,"&","&");

    text= replaceAll(text,"’","’");




private String replaceAll(String source, String pattern, String replacement) {
        if (source == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        int index;
        int patIndex = 0;
        while ((index = source.indexOf(pattern, patIndex)) != -1) {
            sb.append(source.substring(patIndex, index));
            sb.append(replacement);
            patIndex = index + pattern.length();
        }
        sb.append(source.substring(patIndex));
        return sb.toString();
    }
Kalai Selvan Ravi
  • 2,846
  • 2
  • 16
  • 28
3

It looks like the Jakarta Commons Lang library's StringEscapeUtils.unescapeHtml() method will do what you are looking for.

ColinE
  • 68,894
  • 15
  • 164
  • 232
  • Actually this, i am developing for j2me(java) App ,Jakarta Commons Lang is not Supported in j2me? – String Jul 27 '12 at 06:05