fanfavorite
fanfavorite

Reputation: 5199

How would I remove all HTML attributes in HTML tags in a string

I am trying to take a string that has HTML, strip out some tags (img, object) and all other HTML tags, strip out their attributes. For example:

<div id="someId" style="color: #000000">
   <p class="someClass">Some Text</p>
   <img src="images/someimage.jpg" alt="" />
   <a href="somelink.html">Some Link Text</a>
</div>

Would become:

<div>
   <p>Some Text</p>
   Some Link Text
</div>

I am trying:

string.replaceAll("<\/?[img|object](\s\w+(\=\".*\")?)*\>", ""); //REMOVE img/object

I am not sure how to strip all attributes inside a tag though.

Any help would be appreciated.

Thanks.

Upvotes: 5

Views: 6493

Answers (4)

Alexander Corwin
Alexander Corwin

Reputation: 1157

/<(/?\w+) .*?>/<\1>/ might work - takes the tag (the matching group) and reads any attributes until the close bracket and replaces it with just the backets and the tag.

Upvotes: 1

BalusC
BalusC

Reputation: 1108722

I would not recommend regex for this if you want to filter specific tags. This is going to be hell of a job and never going to be fully reliable. Use a normal HTML parser like Jsoup. It offers the Whitelist API to clean up HTML. See also this cookbook document.

Here's a kickoff example with help of Jsoup which only allows <div> and <p> tags next to the standard set of tags of the chosen Whitelist which is Whitelist#simpleText() in the below example.

String html = "<div id='someId' style='color: #000000'><p class='someClass'>Some Text</p><img src='images/someimage.jpg' alt='' /><a href='somelink.html'>Some Link Text</a></div>";
Whitelist whitelist = Whitelist.simpleText(); // Whitelist.simpleText() allows b, em, i, strong, u. Use Whitelist.none() instead if you want to start clean.
whitelist.addTags("div", "p");
String clean = Jsoup.clean(html, whitelist);
System.out.println(clean);

This results in

<div>
   <p>Some Text</p>Some Link Text
</div>

See also:

Upvotes: 9

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You can remove all attributes like this:

string.replaceAll("(<\\w+)[^>]*(>)", "$1$2");

This expression matches an opening tag, but captures only its header <div and the closing > as groups 1 and 2. replaceAll uses references to these groups to join them back in the output as $1$2. This cuts out the attributes in the middle of the tag.

Upvotes: 8

Churk
Churk

Reputation: 4637

Probably would be much easier if you are using a SAX or DOM, and take the node name and value, and remove all attributes.

Upvotes: -1

Related Questions