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:
<p>Hello world!</p>
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:
<p>Hello world!</p> <a href='https://example.com'>Visit example.com</a>
Note that the '
character in the URL is escaped as '
. 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("<", "<").replaceAll(">", ">") println escapedStr
This code replaces the <
and >
characters with the corresponding XML entities <
and >
, respectively. The output will be:
<p>Hello world!</p>
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("<", "<") .replaceAll(">", ">") .replaceAll("'", "'") .replaceAll('"', """) println escapedStr
In this code, we replace the <
, >
, '
, and "
characters with the corresponding XML entities <
, >
, '
, and "
, respectively. The output will be:
<p>Hello world!</p> <a href='https://example.com'>Visit example.com</a>
To escape HTML characters online, use this tool.
Related:
- Check if String is Empty in Groovy
- Check if Variable is Null in Groovy
- Check if String Contains a Substring in Groovy