Java HTML Escape escapeHTMLTagCopy(String text)

Here you can find the source of escapeHTMLTagCopy(String text)

Description

Replace characters having special meaning inside HTML tags with their escaped equivalents, using character entities such as '&'.

License

BSD License

Parameter

Parameter Description
text input text to be escaped

Return

result the escaped text

Declaration

public static String escapeHTMLTagCopy(String text) 

Method Source Code

//package com.java2s;
//License from project: BSD License 

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class Main {
    /**/*from   w  w  w .  ja v  a 2s.  co  m*/
     * Replace characters having special meaning inside HTML tags
     * with their escaped equivalents, using character entities such as '&'.
     *
     * The escaped characters are :
     *  < > " ' \ &
     *
     * This method ensures that arbitrary text appearing inside a tag does not "confuse"
     * the tag. For example, HREF='Blah.do?Page=1&Sort=ASC'
     * does not comply with strict HTML because of the ampersand, and should be changed to
     * HREF='Blah.do?Page=1&amp;Sort=ASC'.
     * This method always returns a new String
     * @param text input text to be escaped
     * @return result the escaped text
     */
    public static String escapeHTMLTagCopy(String text) {
        final StringBuffer result = new StringBuffer();

        final StringCharacterIterator iterator = new StringCharacterIterator(text);
        char character = iterator.current();
        while (character != CharacterIterator.DONE) {
            if (character == '<') {
                result.append("&lt;");
            } else if (character == '>') {
                result.append("&gt;");
            } else if (character == '\"') {
                result.append("&quot;");
            } else if (character == '\'') {
                result.append("&#039;");
            } else if (character == '\\') {
                result.append("&#092;");
            } else if (character == '&') {
                result.append("&amp;");
            } else {
                //the char is not a special one
                //add it to the result as is
                result.append(character);
            }
            character = iterator.next();
        }
        return result.toString();
    }
}

Related

  1. escapeHtml(String s)
  2. escapeHTML(String text)
  3. escapeHTML(String text)
  4. escapeHTMLLine(String line)
  5. escapeHTMLSpecialChars(String aText)
  6. htmlEscape(final String text)
  7. htmlEscape(Object obj)
  8. htmlEscape(String html)
  9. htmlescape(String html)