Mip
Mip

Reputation: 49

Escape characters in string exclude html tags

Is there any way how to escape in Java characters in string which contains html tags which i want not to escape? For example in string I have

<h1>a b c d ö</h1>

and I need to get:

<h1>a b c d &ouml</h1>

Upvotes: 2

Views: 2354

Answers (2)

Hans Miranda
Hans Miranda

Reputation: 11

Check this:

String textIn = "<h1>a b c d ö</h1>";

String textOut = StringEscapeUtils.escapeHtml4(textIn);

println textOut: &lt;h1&gt;a b c d &ouml;&lt;/h1&gt


For xml or tags:

String textIn = "<h1>a b c d ö</h1>";

String textOut = StringEscapeUtils.unescapeXml(StringEscapeUtils.escapeHtml4(textIn));

println: textOut <h1>a b c d &ouml;</h1>

Upvotes: 1

walkeros
walkeros

Reputation: 4942

See:

https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html#escapeHtml4%28java.lang.String%29

  public static void main(String[] args) {
    String s = "a b c d ö";
    System.out.println(StringEscapeUtils.escapeHtml4(s));
  }

Upvotes: 0

Related Questions