jQuery remove tag from HTML String without RegEx

前端 未结 6 1625
情话喂你
情话喂你 2020-12-05 14:25

So I have following string:

var s = \'Some Text Some other Text\';

The result should be a string with the content

相关标签:
6条回答
  • 2020-12-05 14:37

    You can wrap your string in a jQuery object and do some sort of a manipulation like this:

    var removeElements = function(text, selector) {
        var wrapped = $("<div>" + text + "</div>");
        wrapped.find(selector).remove();
        return wrapped.html();
    }
    

    USAGE

    var removedSpanString = removeElements("<span>Some Text</span> Some other Text", "span");
    

    The beauty of this approach is that you can specify a jquery selector which to remove. i.e. you may wish to remove the <th> in a string. This would be very handy in that case. Hope this helps!

    0 讨论(0)
  • 2020-12-05 14:40

    A very simple approach:

    var html = '<span>Remove <b>tags &amp; entities</b></span>';
    var noTagText = $(html).text();
    // ==> noTagText = 'Remove tags & entities'
    

    Note that it will remove tags but also html entities.

    0 讨论(0)
  • 2020-12-05 14:41

    This may suit your needs:

    <([^ >]+)[^>]*>.*?</\1>|<[^/]+/>
    

    Regular expression visualization

    Debuggex Demo

    In JavaScript:

    $s = s.replace(/<([^ >]+)[^>]*>.*?<\/\1>|<[^\/]+\/>/ig, "");
    

    It also removes self-closing tags (e.g. <br />).

    0 讨论(0)
  • 2020-12-05 14:43

    Just remove html tag like this

    DEMO

    var s = '<span>Some Text</span> Some other Text';
    var r = /<(\w+)[^>]*>.*<\/\1>/gi;
    s.replace(r,"");
    

    Answer given over here :http://www.webdeveloper.com/forum/showthread.php?t=252483

    0 讨论(0)
  • 2020-12-05 14:44

    Just do the following:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    
    <script>
    $(document).ready(function(){
     $("span").not("span div").each(
     function(index, element) {
    $("span").remove();
     }
     );
     });
    
    </script>
    
    <span>Some Text</span> Some other Text
    
    0 讨论(0)
  • 2020-12-05 14:46

    Check link

    e.g. More Specific to your case :-

    var s = '<span>Some Text</span> Some other Text';
    var $s = s.replace(/<span>(.*)<\/span>/g, "");
    
    0 讨论(0)
提交回复
热议问题