How to escape special characters in java?

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));
 
	}	
}

Result

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

Reference

http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html

Tags :

About the Author

mkyong
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.

Comments

  • Swati Rohilla

    This is the BEST example. It helped me alot. Thanks alot. Big thanks to you.