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 : < > " &

Reference

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

About the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
Kiril ISAKOV
Guest
Kiril ISAKOV

Reference is a dead link.
I found the working link: http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html
Please edit.
All best.

bluelurker
Guest
bluelurker

How to escape special characters only from the value. ?
hello$ed
should be helloed

Badal
Guest
Badal

Actually the output is not right. Escaped should be < > " &.

priya
Guest
priya

I want to know about this library commons-lang.jar . I am working on jboss-eap-5.1 on server. Can I download this version jar file?

michael
Guest
michael

how to escape special characters from xml file?

jesus israel perales martinez
Guest
jesus israel perales martinez

StringEscapeUtils.escapeXml(string);

Swati Rohilla
Guest
Swati Rohilla

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