1

我有一个 DIV 元素,其中填充了我要删除的一堆 HTML 实体:

<div class="text">
<p>&lt;p&gt;&#8203;&lt;span style="line-height:25px;"&gt;&#8203;&lt;/span&gt;&lt;span style="line-height:25px;"&gt;&#8203;Hej hop!&lt;/span&gt;&nbsp;&lt;span style="line-height:25px;"&gt;&#8203;&lt;/span&gt;&lt;span</p>
</div>

我正在使用 jQuery 并创建了这段代码,但它不起作用:

$('.text').each(function () {
    $(this).replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, "");
});

我正在尝试用短语“Hej Hop!”替换文本。

正则表达式没有错..

以下是我对其他页面的处理方式:

    text = text.replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, "");

但这是在一个带有返回文本的参数的 javascript 函数中。但在这个特定页面上,我需要使用 jquery 并迭代和检查......

已解决的问题:

$('text').each(function () {
    $(this).html(function (i, v) {
        return $('<div>').html(v).text();
    });
});
4

3 回答 3

7

您只需要:

$('.text').empty();

编辑——如果你想从元素的内容中删除标记,最简单的做法就是 Marc B 在评论中建议的:

$('.text').each(function() {
  $(this).text($(this).text());
});
于 2013-03-11T16:13:20.973 回答
2

您可以使用.html()像这样剥离它们

$('div.text').html(function(i,v){
    return $('<div>').html(v).text();
    // create new div - append HTML and get the text from the div
});

http://jsfiddle.net/UA9P9/

它仍然在其中留下一些字符,因此您可能需要使用正则表达式将它们正则表达式

$('div.text').html(function(i,v){
     return $.trim($('<div>').html(v).text().replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, ""));
});

http://jsfiddle.net/VfxaT/

于 2013-03-11T16:30:07.977 回答
0

这些是 Ascii 代码,因此正则表达式是:/xxx[\x00-\x7F]+xxx/

于 2013-03-11T16:17:12.600 回答