Let's say there's a string of HTML, with script tags, plain text, whatever.
What's the best way to strip out only the <a>
tags?
I've been using some methods here, but these are for all tags. Strip HTML from Text JavaScript
Let's say there's a string of HTML, with script tags, plain text, whatever.
What's the best way to strip out only the <a>
tags?
I've been using some methods here, but these are for all tags. Strip HTML from Text JavaScript
A <a> tag is not supposed to hold any other <a> tag, so a simple ungreedy regexp would do the trick (i.e.
string.match(/<a>(.*?)<\/a>/)
, but this example suppose the tags have no attribute).Using jQuery:
Adding a wrapping
<div>
tag allows us to get the desired HTML back.I wrote a more detailed explanation on my blog.
Here's a native (non-library) solution if performance is a concern.
Use it like this:
This approach will preserve existing DOM nodes, minimizing side-effects if you have elements within the anchors that have events attached to them.
To use (with jQuery):
To use (without jQuery):