Java HTML Escape htmlEscape(String str)

Here you can find the source of htmlEscape(String str)

Description

Escape ampersands and less-than characters in a string using HTML-style & and < constructs.

License

Apache License

Parameter

Parameter Description
str the string to be escaped.

Return

the escaped string.

Declaration


public static String htmlEscape(String str) 

Method Source Code

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

public class Main {
    /**//from www. jav a  2  s  . c  om
     * Escape ampersands and less-than characters in a string using HTML-style & and < constructs.
     *
     * @param str the string to be escaped.
     * @return the escaped string.
     */

    public static String htmlEscape(String str) {

        String rval = "";
        String s = str;
        while (true) {

            int ix1 = s.indexOf((int) '&');
            int ix2 = s.indexOf((int) '<');
            if (ix1 < 0 && ix2 < 0) {

                break;

            }

            int ix;
            if (ix1 < 0) {

                ix = ix2;

            } else if (ix2 < 0) {

                ix = ix1;

            } else {

                ix = ix1 < ix2 ? ix1 : ix2;

            }

            rval += s.substring(0, ix);
            s = s.substring(ix);
            if (s.startsWith("&")) {

                rval += "&amp;";

            } else {

                rval += "&lt;";

            }

            s = s.substring(1);

        }

        rval += s;

        return rval;

    }
}

Related

  1. htmlEscape(String S)
  2. htmlEscape(String s)
  3. htmlescape(String s)
  4. htmlEscape(String source)
  5. htmlEscape(String str)
  6. htmlEscape(String str)
  7. htmlEscape(String string)
  8. htmlEscape(String tag)
  9. htmlEscape(String text)