Escape HTML Characters in Groovy

Escape HTML Characters in Groovy

  • Groovy
  • 3 mins read

To escape HTML characters in Groovy, you can use the StringEscapeUtils.escapeHtml() method from the org.apache.commons.lang3 library. Here's an example:

Escape HTML Characters in Groovy using StringEscapeUtils Example

import org.apache.commons.lang3.StringEscapeUtils

def str = "<p>Hello world!</p>"
def escapedStr = StringEscapeUtils.escapeHtml(str)
println escapedStr

This code escapes the HTML characters in the string str. The output will be:

&lt;p&gt;Hello world!&lt;/p&gt;

Here's another example that shows how to escape multiple HTML characters in a string:

import org.apache.commons.lang3.StringEscapeUtils

def str = "<p>Hello world!</p> <a href='https://example.com'>Visit example.com</a>"
def escapedStr = StringEscapeUtils.escapeHtml(str)
println escapedStr

In this code, we escape all the HTML characters in the string str, including the <p>, </p>, <a>, and </a> tags, as well as the ' character in the URL. The output will be:

&lt;p&gt;Hello world!&lt;/p&gt; &lt;a href=&apos;https://example.com&apos;&gt;Visit example.com&lt;/a&gt;

Note that the ' character in the URL is escaped as &apos;. This is because the escapeHtml() method uses the XML entities for escaping HTML characters.

Escaping HTML Characters using replaceAll Function in Groovy

To escape a string in Groovy without using StringEscapeUtils, you can use the replaceAll() method and specify the characters you want to escape. Here's an example that shows how to escape HTML characters:

def str = "<p>Hello world!</p>"
def escapedStr = str.replaceAll("<", "&lt;").replaceAll(">", "&gt;")
println escapedStr

This code replaces the < and > characters with the corresponding XML entities &lt; and &gt;, respectively. The output will be:

&lt;p&gt;Hello world!&lt;/p&gt;

Here's another example that shows how to escape multiple HTML characters in a string:

def str = "<p>Hello world!</p> <a href='https://example.com'>Visit example.com</a>"
def escapedStr = str
  .replaceAll("<", "&lt;")
  .replaceAll(">", "&gt;")
  .replaceAll("'", "&apos;")
  .replaceAll('"', "&quot;")
println escapedStr

In this code, we replace the <, >, ', and " characters with the corresponding XML entities &lt;, &gt;, &apos;, and &quot;, respectively. The output will be:

&lt;p&gt;Hello world!&lt;/p&gt; &lt;a href=&apos;https://example.com&apos;&gt;Visit example.com&lt;/a&gt;

To escape HTML characters online, use this tool.

Related:

  1. Check if String is Empty in Groovy
  2. Check if Variable is Null in Groovy
  3. Check if String Contains a Substring in Groovy