SFernando
SFernando

Reputation: 1124

Escape html anchor tags with [href]

How to escape each html dynamic anchor tag if URLs are different?

<a href="*_url">*_url</a>

I need the above code to be saved in the database as

&lt;a href="*_url"&gt;*_url&lt;/a&gt;

I've escaped other tags like <code>,<html>,<strong>... using

`StringUtils.replaceEach(post, search, replacement);` 

Because they are static tags. But the anchor tag holds "href" as dynamic content.

How can I get this done by a Javamethod at once.

Thanks!

Upvotes: 1

Views: 1995

Answers (4)

Hartmut Pfarr
Hartmut Pfarr

Reputation: 6139

David Grant's solution seems correct to me. In the meantime escapeHtml has gotten obsolete. You can choose between escapeHtml3 and escapeHtml4.

1) Add to Your Gradle Dependency List:

compile 'org.apache.commons:commons-lang3:3.3.2'

For Maven it is:

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>

2)

import org.apache.commons.lang3.StringEscapeUtils;

3) Then invoke...

StringEscapeUtils.escapeHtml4(...)

Upvotes: 0

SFernando
SFernando

Reputation: 1124

using an XML/HTML parser and getting the text within the two tags is easy.

i got it here

Upvotes: 0

David Grant
David Grant

Reputation: 14223

Use StringEscapeUtils.escapeHtml() from Apache Commons Lang.

Upvotes: 1

Sandeep Pathak
Sandeep Pathak

Reputation: 10747

You can use java.net.URLEncoder.encode on conjunction with your StringUtils.replaceEach. You may want to parse the anchor tag and encode the same using URLEncoder .

Upvotes: 0

Related Questions