0

I want to escape $ symbol along with other characters like '<', '>' etc. So just wanted to know if StringEscapeUtils supported this. And if not, how can I escape it?

Malte Hartwig
  • 4,477
  • 2
  • 14
  • 30
mmk
  • 480
  • 3
  • 10

2 Answers2

1

Looks like no. You can try it with this code:

StringEscapeUtils.escapeHtml("<b>Hello, World!</b>$")

Outputs

&lt;b&gt;Hello, World!&lt;/b&gt;$
Nick
  • 823
  • 2
  • 10
  • 22
1

I tested doing the following from commons-text 1.1 after commons-lang 3 deprecated StringEscapeUtils:

public static void main(String[] args)
{
    System.out.println(StringEscapeUtils.escapeHtml4("$ % > < = #"));
}

Output $ % &gt; &lt; = #

It does not escape "$" out of the box, but the new Utils in commons-text enable users to extend it. Read this article for examples. Here is a small one, but the article shows more advanced possibilities:

Map<CharSequence, CharSequence> added = new HashMap<>();
added.put("$", "foo");
System.out.println(StringEscapeUtils.ESCAPE_HTML4
                                    .with(new LookupTranslator(added))
                                    .translate("$ % > < = #"));

Output foo % &gt; &lt; = #

technocrat
  • 3,513
  • 5
  • 25
  • 39
Malte Hartwig
  • 4,477
  • 2
  • 14
  • 30
  • If I want to do it manually (using replaceAll) what should be the value, any idea? – mmk Dec 01 '17 at 09:26
  • Whether you do it manually or with the escape utils, the code you found and mentioned in your reply to Joop should be the one. The percent encoded one is for URLs. – Malte Hartwig Dec 01 '17 at 09:58