Reputation: 819
Is there a standard class in Java that has a method to HTML-escape a string?
< ... <
> ... >
Upvotes: 3
Views: 514
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
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("<"+(int)c+";");
}
else if(c=='>'){
out.append(">"+(int)c+";");
}
else
{
out.append(c);
}
}
return out.toString();
}
Upvotes: 0
Reputation: 75356
No but you could write one:
Iterate over string:
>
<
&
&#...;
where ... is the char unicode value. Upvotes: 0