All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.minidev.fomat.HtmlFormat Maven / Gradle / Ivy

The newest version!
package net.minidev.fomat;

/**
 * Basic HTML helper
 * 
 * @author Uriel Chemouni
 * 
 */
public class HtmlFormat {
	/**
	 * escape XML chars > < &
	 * 
	 * if (text stay unchanged return the original text)
	 * 
	 * @param text
	 * 
	 * @return the string widthout & < >
	 */
	public static String escapeHtml(String text) {
		StringBuilder sb = new StringBuilder(text.length());

		for (char c : text.toCharArray()) {
			if (c == '&')
				sb.append("&");
			else if (c == '>')
				sb.append(">");
			else if (c == '<')
				sb.append("<");
			else
				sb.append(c);
		}
		if (sb.length() == text.length())
			return text;
		return sb.toString();
	}

	public static String unEscapeHtml(String text) {
		text = text.replace(">", ">");
		text = text.replace("<", "<");
		text = text.replace("&", "&");
		return text;
	}

	/**
	 * escape XML chars > < &
	 * 
	 * append string widthout & < >
	 */
	public static StringBuilder escapeHtml(StringBuilder sb, String text) {
		int len = text.length();
		for (int i = 0; i < len; i++) {
			char c = text.charAt(i);
			if (c == '&')
				sb.append("&");
			else if (c == '>')
				sb.append(">");
			else if (c == '<')
				sb.append("<");
			else
				sb.append(c);
		}
		return sb;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy