在JQuery中从字符串中移除动态字符串

Removing a dynamic string from a string in JQuery

本文关键字:字符串 动态 JQuery      更新时间:2023-09-26

我有一个html字符串,其中包括一个表标记。在table标签中可以有各种各样的标签(tr/td等)。

如何从字符串中删除标签,同时保留html的其余部分?

Ie:

如果字符串是

"<p>testing<table><tr><td>cell 1</td></tr></table> a table</p>" 

那么我希望结果是

"<p>testing a table</p>" 
编辑:

提供更多细节:我无法控制html, p只是一个例子,它可以是标签的任何组合或(尽管只有一个表)

之外的纯文本。编辑2:

参见上面的"如何从字符串中删除标签,同时保留html的其余部分?"这意味着,如果(在表外)有一个元素被加粗或强调,那么该标签不应该停止

简单地删除所有标记,然后将剩下的(原始文本)附加在p元素内。没有正则表达式,没有火箭科学

使用remove方法

这将工作,如果浏览器允许你把一个块元素,如tablep:
var p_el = $("<p>testing<table><tr><td>cell 1</td></tr></table> a table</p>")
# Note: This gets slit into 3 elements: p, table, p. This would not
#       happen with a table inside a block element like a `div`
# Find all table elements and remove them:
p_el.find('table').remove()
# If you want the string back you can do:
p_el[0].outerHTML  # p_el[0] gets the DOM object from the jQuery object
# If the string has already been rendered, then of course you should use the 
# appropriate selector to find the `table` elements within `p` elements and then remove them:
$('.someParentEl p table').remove()
# If you need to remove multiple types of elements, then a more elaborate
# selector can be used within remove. I recommend reading up on jQuery selectors
# But an example might be to exclude div tags as well:
$('.someParentEl p').find('table, div').remove()
# What I suspect is that you actually want to remove all block elements from the string
# (table, div, etc. leaving b, i, strong, span, etc.):
$('.someParentEl p *').filter(function(index) {return $(this).css("display") === 'block'}).remove()
# Note: This will only work on elements already in the DOM.

相关:为什么


<lt;p>
和:在

标签……对还是错?

如果你确实在处理DOM段落内的表,那么这是一个完整的另一个蠕虫罐头,我不确定如何始终如一地清理客户端的混乱。

如果p在你的例子中只是一个不幸的选择,那么我所有的例子都应该用p代替。

查询简单易懂。

但是table不应该包含在p标签里面。您需要使用其他HTML标记。我用div代替p标签。

var stag="<div>testing<table><tr><td>cell 1</td></tr></table> a table</div>";
function removeTag(text, selector) {
    var content= $(text);
    content.find(selector).remove();
    return content.text();
}
var pString = removeTag(stag, "table");
alert(pString);

您可以使用下面的代码来删除标签。

$('tag_to_remove').contents().unwrap();

检查这个小提琴

我认为你的html输出是错误的当你在浏览器中执行这个html时它会显示如下

 <p>testing</p>
    <table>
        <tbody>
            <tr>
                <td>cell 1</td>
            </tr>
        </tbody>
    </table>
    a table

所以当你试图在"p"标签中获取文本时,你只会得到"testing"作为输出。如果html是正确的,那么你可以尝试使用using

删除表
$('p table').remove();

那么你就能得到想要的输出。