Friday, 8 March 2019

Java: Escape string using html entities


StringEscapeUtils class provides below methods to escape string using HTML entities.
public static final String escapeHtml4(final String input)
public static final String escapeHtml3(final String input)

App.java
package com.sample;

import org.apache.commons.text.StringEscapeUtils;

public class App {

 public static void main(String args[]) {
  String template1 = "<html> <head></head</html>";
  String template2 = "Hello &nbsp; World";
  
  String result1 = StringEscapeUtils.escapeHtml4(template1);
  String result2 = StringEscapeUtils.escapeHtml4(template2);
  
  System.out.println(template1 + " is converted to " + result1);
  System.out.println(template2 + " is converted to " + result2);
 }
}

Output
<html> <head></head</html> is converted to &lt;html&gt; &lt;head&gt;&lt;/head&lt;/html&gt;
Hello &nbsp; World is converted to Hello &amp;nbsp; World

Dependency Used
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.6</version>
</dependency>


You may like


No comments:

Post a Comment