Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Escape Special Characters in String Using Java Library

We can use Apache's commons-text library to escape the special characters in HTML entities. Before moving further, we will first understand what are special characters and what does escaping of special characters mean.

What are Special Characters?

Below is the list of special characters:

&
>
 
"

Read Also: Escape Sequences in Java

What does Escaping of Special Characters mean?

Escaping of Special characters means replacing them with HTML character-entities. For example:

Symbol HTML Entities Name
&
&
>
>
<
"
"

Add Dependency:

Add the below dependency to your pom.xml. The below dependency can be used with Java8+. You can check the latest version here.


org.apache.commons
commons-text
1.9


We will use StringEscapeUtils.escapeHtml4() method to escape special characters in String.

Note: Use org.apache.commons.text.StringEscapeUtils instead of org.apache.commons.lang3.StringEscapeUtils because later class is deprecated.

Java Program:

Below is the Java Program for escaping special characters in String using commons-text java library.

import org.apache.commons.text.StringEscapeUtils;

public class JavaHungry {
public static void main(String args[]) {
// Given special character
String testString = " & \" ";
// Escape special character using StringEscapeUtils class
String outputString = StringEscapeUtils.escapeHtml4(testString);
// Printing the output
System.out.println("Special Characters : "+ testString +"\n Escaped Output : "+outputString);
}
}

Output:
Special Characters :     &   " 
Escaped Output :  <   >   &   "

That's all for today, please mention in the comments in case you have any queries regarding escaping special characters in String using the commons-text Java library.


This post first appeared on Java Hungry, please read the originial post: here

Share the post

Escape Special Characters in String Using Java Library

×

Subscribe to Java Hungry

Get updates delivered right to your inbox!

Thank you for your subscription

×