/******************************************************************************* * Copyright (c) 2016 Association for Decentralized Information Management * in Industry THTH ry. * 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: * THTH ry - initial API and implementation *******************************************************************************/ package org.simantics.debug.browser.utils; public class Escapes { public static String html(String s) { if (!containsAnyOf(s, HTML_CHARS_TO_ESCAPE)) return s; return batchReplace(s, HTML_CHARS_TO_ESCAPE, HTML_CHAR_REPLACEMENTS); } private static final char[] HTML_CHARS_TO_ESCAPE = { '&', '<', '>', '\n' }; private static final String[] HTML_CHAR_REPLACEMENTS = { "&", "<", ">", "
" }; private static boolean containsAnyOf(String s, char[] chars) { int l = s.length(); for (int i = 0; i < l; ++i) { char p = s.charAt(i); for (char ch : chars) if (p == ch) return true; } return false; } private static String batchReplace(String s, char[] charsToReplace, String[] replacements) { int l = s.length(); int rl = charsToReplace.length; StringBuilder sb = new StringBuilder(l*2); nextChar: for (int i = 0; i < l; ++i) { char p = s.charAt(i); for (int j = 0; j < rl; ++j) { if (p == charsToReplace[j]) { sb.append(replacements[j]); continue nextChar; } } sb.append(p); } return sb.toString(); } public static void main(String[] args) { System.out.println(html("><&\nfoobar\n<>")); } }