-3

I'd like to filter an html String before loading it in a WebView:

I'd like to remove all the img tags with the param:

data-custom:'delete'

In example

<img src="https://..." data-custom:'delete'/>

How can I do this in Android in a elegant way (without external libraries if possible)

Addev
  • 31,819
  • 51
  • 183
  • 302

1 Answers1

1

I'm going to go for a nice and simple:

String element = "<img src='https://...' data-custom:'delete'/>";
String attributeRemoved = element.replaceAll("data-custom:['|\"].+['|\"]", "");

Updated based on comment

If you want to remove the whole tag you can do this:

String elementRemoved = element.replaceAll("<.*data-custom:['|\"].+['|\"].*>", "");

If you only want to do it for <img> tags you can do:

String imgElementRemoved = element.replaceAll("<img.*data-custom:['|\"].+['|\"].*>", "");

A much more reliable way would be to parse the HTML as an XML document and use XPath to find all elements with a data-custom attribute and remove them from the document, then save the updated document. While you can do this stuff with regex, it's not normally a good idea...

Ardesco
  • 7,281
  • 26
  • 49
  • I want to delete the whole img tag. will update the question – Addev Apr 12 '19 at 12:52
  • "Remove a given tag from a html string **without replace**"... so the last part of the answer is the only intersting one but not the elaborate enough. – AxelH Apr 12 '19 at 13:37
  • That sounds like useful pertinent information that should be added to the question. Why do you not want to use the replaceAll method from Java? You are now effectively asking how to perform a replacement without doing a replace? – Ardesco Apr 12 '19 at 14:25