Java HTML Escape escapeHTML(String s)

Here you can find the source of escapeHTML(String s)

Description

escape HTML

License

Open Source License

Declaration

public static String escapeHTML(String s) 

Method Source Code

//package com.java2s;
// under the terms of the GNU Lesser General Public License as published

import java.util.HashMap;
import java.util.Map;

public class Main {
    private static Map<String, Character> _entities;
    private static Map<Character, String> _unentities;

    public static String escapeHTML(String s) {
        if (s == null)
            return "";
        StringBuffer sb = new StringBuffer(s.length() + 100);
        Map<Character, String> unent = getHtmlUnEntities();
        for (int ii = 0, ll = s.length(); ii < ll; ii++) {
            char ch = s.charAt(ii);
            String ent = unent.get(ch);
            if (ent != null) {
                sb.append("&").append(ent).append(";");
            } else {
                sb.append(ch);/*from  w w w .  ja v  a 2 s.c  om*/
            }
        }
        return sb.toString();
    }

    private static synchronized Map<Character, String> getHtmlUnEntities() {
        if (_unentities == null) {
            _unentities = new HashMap<Character, String>();
            for (Map.Entry<String, Character> entry : getHtmlEntities().entrySet()) {
                _unentities.put(entry.getValue(), entry.getKey());
            }
        }
        return _unentities;
    }

    private static synchronized Map<String, Character> getHtmlEntities() {
        if (_entities == null) {
            _entities = new HashMap<String, Character>();
            _entities.put("lt", '<');
            _entities.put("gt", '>');
            _entities.put("amp", '&');
            _entities.put("quot", '"');
            _entities.put("apos", '\'');
            _entities.put("nbsp", '\u00A0');
            _entities.put("shy", '\u00AD');
            _entities.put("copy", '\u00A9');
            _entities.put("reg", '\u00AE');
            _entities.put("trade", '\u2122');
            _entities.put("mdash", '\u2014');
            _entities.put("ndash", '\u2013');
            _entities.put("ldquo", '\u201C');
            _entities.put("rdquo", '\u201D');
            _entities.put("euro", '\u20AC');
            _entities.put("middot", '\u00B7');
            _entities.put("bull", '\u2022');
            _entities.put("laquo", '\u00AB');
            _entities.put("raquo", '\u00BB');
        }
        return _entities;
    }
}

Related

  1. escapeHTML(String aText)
  2. escapeHtml(String s)
  3. escapeHTML(String s)
  4. escapeHtml(String s)
  5. escapeHTML(String text)