简体   繁体   中英

Trying to remove all html from a element with jquery

I have a DIV element that's filled with a bunch of HTML entities that I want to remove:

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

I'm using jQuery and created this code but it isn't working:

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

I'm trying to replace the text with the phrase "Hej Hop!".

The regex is not wrong..

Here is how I did it with some other pages:

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

But this was in a javascript function with parameters that returned the text.. But on this specific page I need to use jquery and iterate and check...

Question Solved:

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

You just need:

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

edit — if you want to remove the markup from the contents of the element, the simplest thing to do would be what Marc B suggested in a comment:

$('.text').each(function() {
  $(this).text($(this).text());
});

You can strip them like this using .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/

It still leaves some characters in there so you will probably need to regex them out with your regex

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

http://jsfiddle.net/VfxaT/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM