Java HTML Encode toHTML(String rawText)

Here you can find the source of toHTML(String rawText)

Description

Turns a string into HTML displayable text by escaping special characters ('<','&' etc...).

License

Open Source License

Declaration


public static String toHTML(String rawText) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//w  w w  .  ja  va2  s  .  co  m
     *    Turns a string into HTML displayable text by escaping
     *    special characters ('<','&' etc...).
     *
     *    ... add new ones as required; or see if an existing ftn somewhere
     *    does this already...
     */

    public static String toHTML(String rawText) {
        String test;
        if (rawText.length() > 14)
            test = rawText.substring(0, 14).toLowerCase();
        else
            test = rawText.toLowerCase();

        if (test.startsWith("<html>") || test.startsWith("<!doctype html>")) {

            // XXX this was commented out, but it seems to be necessaary/desirable?
            if (test.startsWith("<html>"))
                rawText = rawText.substring(6);
            else if (test.startsWith("<!doctype html>"))
                rawText = rawText.substring(15);

            if (rawText.toLowerCase().endsWith("</html>")) {
                rawText = rawText.substring(0, rawText.length() - 7);
            }

            // END XXX

            return rawText;
        }
        char C;
        StringBuffer temp = new StringBuffer(rawText);

        for (int pos = 0; pos < temp.length(); pos++) {
            C = temp.charAt(pos);

            switch (C) {
            case '<':
                replaceChar(temp, pos, "&lt;");
                break;
            case '>':
                replaceChar(temp, pos, "&gt;");
                break;
            case '&':
                replaceChar(temp, pos, "&amp;");
                break;
            case '\"':
                replaceChar(temp, pos, "&quot;");
                break;
            }
        }
        return temp.toString();
    }

    /**
     *    Deletes a character in <i>text</i> at position <i>pos<i> and replaces
     *    it with the string <i>replacement</i>.
     *
     *    @param text the text to be modified
     *    @param pos the position of the character to be deleted
     *    @param replacement the string the character is to be replaced with.
     */

    public static int replaceChar(StringBuffer text, int pos, String replacement) {
        text.deleteCharAt(pos);
        text.insert(pos, replacement);
        return (pos + replacement.length());
    }
}

Related

  1. toHtml(String message)
  2. toHTML(String msg)
  3. toHTML(String org, boolean inputValue)
  4. toHtml(String p_str)
  5. toHTML(String plainText)
  6. toHTML(String s)
  7. toHtml(String s)
  8. toHtml(String str)
  9. toHtml(String str)