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

发布于 2024-10-08 22:25:14 字数 233 浏览 0 评论 0原文

假设有一个 HTML 字符串,带有脚本标记、纯文本等。

仅删除 标签的最佳方法是什么?

我在这里使用了一些方法,但这些方法适用于所有标签。 从文本 JavaScript 中剥离 HTML

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

冰葑 2024-10-15 22:25:14

使用 jQuery:

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

添加一个包装

标签使我们能够获取所需的 HTML。

我在博客上写了更详细的解释

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.

这种方法将保留现有的 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]);
}

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]);
}
请持续率性 2024-10-15 22:25:14

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

可遇━不可求 2024-10-15 22:25:14

如果性能是一个问题,这里有一个本机(非库)解决方案。

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

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' ) );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文