Often times, we encountered some special characters or arbitrary text placed in an HTML tag that resulting an invalid HTML output. The special characters often needs to be altered or escape to ensure the resulting HTML is still valid.

Special characters as follow
1) <
2) >
3) ”
4) ‘
5) \
6) &

Here i want to introduce a handy-ready java library call StringEscapeUtils which included in commons-lang.jar library, and used to escape special characters in Java.

P.S Please download the commons-lang.jar library in http://commons.apache.org/lang/

Here is the source code to demonstrate how to escape special characters with StringEscapeUtils class.

import org.apache.commons.lang.StringEscapeUtils;
public class testEscapeHTML{
	public static void main(String args[]){
		String testStr = "< > \" &";
		System.out.println("Original : " + testStr);
		System.out.println("Escaped : " + StringEscapeUtils.escapeHtml(testStr));


Original : < > " &
Escaped : &lt; &gt; &quot; &amp;



Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Related Posts

Popular Posts