0

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

1
  • Do you want to preserve the contents of the tags?
    – SLaks
    Dec 27, 2010 at 2:49

4 Answers 4

4

Using jQuery:

var content = $('<div>' + htmlString + '</div>');
content.find('a').replaceWith(function() { return this.childNodes; });
var newHtml = content.html();

Adding a wrapping <div> tag allows us to get the desired HTML back.

I wrote a more detailed explanation on my blog.

6
  • This may cause unexpected side-effects, such as breaking event handlers attached to any of the elements touched. Dec 27, 2010 at 3:06
  • @eyelidlessness: He has a string. There aren't any event handlers. Had he not had a string, fixed.
    – SLaks
    Dec 27, 2010 at 3:07
  • @SLaks, thanks for pointing that out, I missed it. I did provide an alternative approach in another answer in case someone is trying to accomplish the same thing within a DOM structure. Dec 27, 2010 at 3:14
  • @eyelidlessness: I think I already fixed that. .contents() returns actual DOM elements, so handlers should be preserved. (I'm too lazy to check)
    – SLaks
    Dec 27, 2010 at 3:19
  • @SLaks, I missed that. Cheers (+1). Dec 27, 2010 at 4:52
3

This approach will preserve existing DOM nodes, minimizing side-effects if you have elements within the anchors that have events attached to them.

function unwrapAnchors() {
    if(!('tagName' in this) || this.tagName.toLowerCase() != 'a' || !('parentNode' in this)) {
        return;
    }
    var childNodes = this.childNodes || [], children = [], child;
    // Convert childNodes collection to array
    for(var i = 0, childNodes = this.childNodes || []; i < childNodes.length; i++) {
        children[i] = childNodes[i];
    }
    // Move children outside element
    for(i = 0; i < children.length; i++) {
        child = children[i];
        if(('tagName' in child) && child.tagName.toLowerCase() == 'a') {
            child.parentNode.removeChild(child);
        } else {
            this.parentNode.insertBefore(child, this);
        }
    }
    // Remove now-empty anchor
    this.parentNode.removeChild(this);
}

To use (with jQuery):

$('a').each(unwrapAnchors);

To use (without jQuery):

var a = document.getElementsByTagName('a');
while(a.length) {
    unwrapAnchors.call(a[a.length - 1]);
}
2
  • var elem = arguments[0] || this
    – SLaks
    Dec 27, 2010 at 3:19
  • 1
    @SLaks, used with jQuery, el would be the iterator. Dec 27, 2010 at 4:49
0

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).

6
  • That won't match any real tag. Also, unclosed <a> tags are valid HTML. (as opposed to XHTML)
    – SLaks
    Dec 27, 2010 at 2:50
  • Yes, I edited my answer. As for the unclosed <a> tags, I didn't know it was valid in HTML. That doesn't really make sense though, and I haven't seen such thing. So the regexp method will work most of the time if you trust the source of the string.
    – Pik'
    Dec 27, 2010 at 2:56
  • <a> tags are also anchors (for # links). Anchors have no content.
    – SLaks
    Dec 27, 2010 at 3:04
  • Why on earth would you trust a string?
    – SLaks
    Dec 27, 2010 at 3:04
  • @SLaks, you might trust a string when you have control over its construction. Dec 27, 2010 at 3:15
0

Here's a native (non-library) solution if performance is a concern.

function stripTag(str, tag) {
    var a, parent, div = document.createElement('div');
    div.innerHTML = str;
    a = div.getElementsByTagName( tag );
    while( a[0] ) {
        parent = a[0].parentNode;
        while (a[0].firstChild) {
            parent.insertBefore(a[0].firstChild, a[0]);
        }
        parent.removeChild(a[0]);
    }
    return div.innerHTML;
}

Use it like this:

alert( stripTag( my_string, 'a' ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.