Java HTML Escape htmlescape(String s)

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

Description

Turns funky characters into HTML entity equivalents

e.g.

License

Apache License

Parameter

Parameter Description
s String to escape

Return

Escaped string

Declaration

public static String htmlescape(String s) 

Method Source Code


//package com.java2s;
/*// w ww  .  j ava 2 s  .  c o m
 *   Copyright 2007 skynamics AG
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

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

public class Main {
    /**
     * Hashtable of special characters.
     */
    private static Map i2e = new HashMap();
    /**
     * Hashtable of escaped characters.
     */
    private static Map masked2html = new HashMap();

    /**
     * Turns funky characters into HTML entity equivalents<p>
     * e.g. <tt>"bread" & "butter"</tt>
     * =>
     * <tt>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</tt>.
     *
     * Supports nearly all HTML entities, including funky accents.
     * See the source code for more detail.
     *
     * In addition, "\n" characters will be converted to HTML line breaks and "\t" to
     * 4 non-breaking spaces.
     *
     * @param s String to escape
     * @return Escaped string
     */
    public static String htmlescape(String s) {
        if (s == null)
            return "";
        StringBuffer buf = new StringBuffer();

        int n = s.length();
        for (int i = 0; i < n; ++i) {
            char ch = s.charAt(i);

            String entity = (String) i2e.get(Integer.valueOf(ch));

            if (entity == null) {
                String htmlEntity = (String) masked2html.get(String.valueOf(ch));
                if (htmlEntity != null) {
                    buf.append(htmlEntity);
                    continue;
                }
            }

            if (entity == null) {
                if (ch > 128) {
                    buf.append("&#" + ((int) ch) + ";");
                } else {
                    buf.append(ch);
                }
            } else {
                buf.append("&" + entity + ";");
            }
        }
        return buf.toString();
    }
}

Related

  1. htmlEscape(String input)
  2. htmlEscape(String nonHTMLsrc)
  3. htmlEscape(String S)
  4. htmlEscape(String s)
  5. htmlEscape(String s)
  6. htmlEscape(String source)
  7. htmlEscape(String str)
  8. htmlEscape(String str)
  9. htmlEscape(String str)