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

io.github.albertus82.net.httpserver.html.HtmlUtils Maven / Gradle / Ivy

Go to download

Java SWT/JFace Utility Library including a Preferences Framework, Lightweight HTTP Server and macOS support.

There is a newer version: 20.1.0
Show newest version
package io.github.albertus82.net.httpserver.html;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class HtmlUtils {

	private static final Set charsToEscapeForEcmaScript = new HashSet<>(Arrays.asList('&', '"', '<', '>', '\'', '/'));

	private HtmlUtils() {
		throw new IllegalAccessError("Utility class");
	}

	public static String escapeEcmaScript(final String unescaped) {
		String escaped = unescaped.replace("\\", "\\\\");
		final Set replacedChars = new HashSet<>();
		for (final char c : escaped.toCharArray()) {
			if (!replacedChars.contains(c) && (c < 0x20 || c > 0x7F || charsToEscapeForEcmaScript.contains(c))) {
				escaped = escaped.replace(Character.toString(c), String.format(c > 0xFF ? "\\u%04X" : "\\x%02X", (int) c));
				replacedChars.add(c);
			}
		}
		return escaped;
	}

	public static String escapeHtml(final String unescaped) {
		return unescaped.replace("&", "&").replace("\"", """).replace("<", "<").replace(">", ">").replace("'", String.format("&#%d;", (int) '\''));
	}

	public static String unescapeHtml(final String escaped) {
		return escaped.replace(String.format("&#%d;", (int) '\''), "'").replace(">", ">").replace("<", "<").replace(""", "\"").replace("&", "&");
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy