My HTMLEncode function in Java

Every now and then I have to work in an environment where imports of frameworks is prohibited and it in times like that that I had to create my own HTMLEncode function. Here is the result:

public static String HTMLEncode(String inputString) {
 
		// Check if string contains ANY special characters (<>"&)
		if(inputString.indexOf("<") != -1 || 
                   inputString.indexOf(">") != -1 || 
                   inputString.indexOf("\"") != -1 ||
                   inputString.indexOf("&") != -1) {
 
			char c;
			StringBuffer out = new StringBuffer();
			for(int i=0; i < inputString.length(); i++) {
 
			    c = inputString.charAt(i);
 
			    if(c=='"' || c=='<' || c=='>') {
			       out.append("&#"+(int)c+";");
			    }
			    else if(c == '&'){
                                // Is &-sign preceding an HTML entity?
			    	if(inputString.indexOf("&amp;", i) == i || 
			    		inputString.indexOf("& #38;", i) == i ||
		    			inputString.indexOf("& lt;", i)  == i || 
		    			inputString.indexOf("& #60;", i) == i ||
		    			inputString.indexOf("& gt;", i)  == i ||
		    			inputString.indexOf("& #62;", i) == i ||
		    			inputString.indexOf("& quot;", i)== i ||
		    			inputString.indexOf("& #34;", i) == i ){
 
			    		out.append(c);
 
			    	}
			    	else {
			    		out.append("&#"+(int)c+";");
			    	}
			    }
			    else {
			        out.append(c);
			    }		
			}			
			return out.toString();
		}
		else {
			return inputString;			
		}				
	}

NOTE! The spaces inside the strings on row 21 thru 27 are only there for displaying purposes. In real code these spaces should be removed

Comments are closed.

Niklas Tech Blog
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.