在给定一个html字符串的情况下,在javascript中仅删除锚定HTML标记的最佳方法是什么?

时间:2010-12-27 02:39:23

标签: javascript jquery html parsing text

假设有一串HTML,带有脚本标签,纯文本等等。

仅剥离<a>代码的最佳方式是什么?

我一直在这里使用一些方法,但这些方法适用于所有标签。 Strip HTML from Text JavaScript

4 个答案:

答案 0 :(得分:3)

使用jQuery:

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

添加换行<div>标记可让我们重新获得所需的HTML。

我在我的博客上写了more detailed explanation

答案 1 :(得分:3)

这种方法将保留现有的DOM节点,如果锚点中的元素附加了事件,则可以最大限度地减少副作用。

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);
}

使用(使用jQuery):

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

使用(不使用jQuery):

var a = document.getElementsByTagName('a');
while(a.length) {
    unwrapAnchors.call(a[a.length - 1]);
}

答案 2 :(得分:0)

A&lt; a&gt;标签不应该包含任何其他&lt; a&gt;标签,所以一个简单的ungreedy regexp就可以了(即string.match(/<a>(.*?)<\/a>/),但是这个例子假设标签没有属性)。

答案 3 :(得分:0)

如果考虑性能,这是一个原生(非库)解决方案。

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;
}

像这样使用:

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