Java HTML Encode htmlEncode(String s)

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

Description

html Encode

License

Open Source License

Return

encoded text, ready to be included in a html text replaces &, ", ', <, > and all whitespace

Declaration

public static String htmlEncode(String s) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010-2015 BSI Business Systems Integration AG.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from  ww w. jav  a2 s  .c  o m
 *     BSI Business Systems Integration AG - initial API and implementation
 ******************************************************************************/

public class Main {
    /**
     * @return encoded text, ready to be included in a html text <xmp>replaces &, ", ', <, > and all whitespace</xmp>
     */
    public static String htmlEncode(String s) {
        return htmlEncode(s, false);
    }

    public static String htmlEncode(String s, boolean replaceSpace) {
        if (s == null) {
            return s;
        }
        if (s.length() == 0) {
            return s;
        }
        s = s.replace("&", "&amp;");
        s = s.replace("\"", "&quot;");
        s = s.replace("'", "&#39;");
        s = s.replace("<", "&lt;");
        s = s.replace(">", "&gt;");
        s = s.replace("\r\n", "<br/>");
        s = s.replace("\n", "<br/>");

        // temporarily replace tabs with specific tab-identifier to not be replaced by subsequent whitespace pattern
        String tabIdentifier = "#TAB#";
        s = s.replace("\t", tabIdentifier);

        if (replaceSpace) {
            s = s.replaceAll("\\s", "&nbsp;");
        }
        s = s.replace(tabIdentifier, "<span style=\"white-space:pre\">&#9;</span>");
        return s;
    }

    public static int length(CharSequence s) {
        if (s == null) {
            return 0;
        } else {
            return s.length();
        }
    }

    /**
     * replace plain text without using regex
     */
    public static String replace(String s, String sOld, String sNew) {
        sNew = (sNew == null ? "" : sNew);
        if (s == null || sOld == null) {
            return s;
        }
        return s.replace(sOld, sNew);
    }
}

Related

  1. htmlEncode(String s)
  2. htmlEncode(String s)
  3. htmlEncode(String s)
  4. htmlEncode(String s)
  5. htmlEncode(String s)
  6. HTMLEncode(String s)
  7. htmlEncode(String s, boolean encodeSpecialChars)
  8. htmlEncode(String s, boolean encodeWS)
  9. HtmlEncode(String str)