RMK
RMK

Reputation: 819

Html escaping in java?

Is there a standard class in Java that has a method to HTML-escape a string?

< ... &lt;
> ... &gt;

Upvotes: 3

Views: 514

Answers (3)

BalusC
BalusC

Reputation: 1108642

No, there isn't. You can use Apache Commons Lang StringEscapeUtils#escapeHtml4 for this.


Update: if you have an aversion against 3rd party libraries and/or prefer homegrowing, then loop over the String's characters and determine the character in a switch and replace it by the escaped character. You can find here and here an example. But still, using StringEscapeUtils is easier on long term.

Upvotes: 8

Alex
Alex

Reputation: 1251

public static String encodeHTML(String s)
{
StringBuffer out = new StringBuffer();
for(int i=0; i<s.length(); i++)
{
     char c = s.charAt(i);
            if( c=='<' )
            {
               out.append("&lt;"+(int)c+";");
            }
            else if(c=='>'){
                 out.append("&gt;"+(int)c+";");
            }
            else
            {
                out.append(c);
            }
}
return out.toString();

}

Upvotes: 0

No but you could write one:

Iterate over string:

  • When char is > output &gt;
  • When char is < output &lt;
  • When char is & output &amp;
  • When char unicode value is outside 32..126 output &#...; where ... is the char unicode value.
  • else output char

Upvotes: 0

Related Questions