删除除<a>之外的html字符串中的所有标记

ArV*_*Van 2 html javascript regex jquery

我有一些html,我必须从所有标签清除,除了一个<a>具有已知类的具体.这是html:

var string = '<span class="so_sentence"><span> Some text <a class="so_footnote-ref" href="#footnote-104008-4" id="footnote-104008-4-backlink">[1]</a></span></span>';
Run Code Online (Sandbox Code Playgroud)

我附加了JQuery,所以我得到了字符串的jQuery对象.

var html = $(string);
Run Code Online (Sandbox Code Playgroud)

现在我必须清除所有跨度的字符串,可能还有其他标签,除了这个<a>:

<a class="so_footnote-ref" href="#footnote-104008-4" id="footnote-104008-4-backlink">[1]</a>
Run Code Online (Sandbox Code Playgroud)

所以我的最终字符串应该是:

'Some text <a class="so_footnote-ref" href="#footnote-104008-4" id="footnote-104008-4-backlink">[1]</a>'
Run Code Online (Sandbox Code Playgroud)

此外,必须可以在结果上调用此函数,因此它必须是适当的类型:

function _trim(string){
    return string.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
}
Run Code Online (Sandbox Code Playgroud)

Har*_*ink 5

试试这个:

$(string).find(':not(a)').contents().unwrap()
Run Code Online (Sandbox Code Playgroud)

这将与每一段HTML代码一起使用.

示例:http://jsfiddle.net/E3RWL/1/

  • OP要求将结果作为HTML**字符串**,否则是一个很好的答案.这将起作用:`var result = $("<div>").append(html).html();`(假设`html`是你当前函数的结果) (3认同)