Remove all HTMLtags in a string (with the jquery text() function)

后端 未结 6 1881
不思量自难忘°
不思量自难忘° 2020-12-03 06:44

is it possible to use the jquery text() function to remove all HTML in a string?

String with HTML tags:
myContent = \'

相关标签:
6条回答
  • 2020-12-03 07:13

    I created this test case: http://jsfiddle.net/ccQnK/1/ , I used the Javascript replace function with regular expressions to get the results that you want.

    $(document).ready(function() {
        var myContent = '<div id="test">Hello <span>world!</span></div>';
        alert(myContent.replace(/(<([^>]+)>)/ig,""));
    });
    
    0 讨论(0)
  • 2020-12-03 07:16
    var myContent = '<div id="test">Hello <span>world!</span></div>';
    
    alert($(myContent).text());
    

    That results in hello world. Does that answer your question?

    http://jsfiddle.net/D2tEf/ for an example

    0 讨论(0)
  • 2020-12-03 07:18

    If you need to remove the HTML but does not know if it actually contains any HTML tags, you can't use the jQuery method directly because it returns empty wrapper for non-HTML text.

    $('<div>Hello world</div>').text(); //returns "Hello world"
    $('Hello world').text(); //returns empty string ""
    

    You must either wrap the text in valid HTML:

    $('<div>' + 'Hello world' + '</div>').text();
    

    Or use method $.parseHTML() (since jQuery 1.8) that can handle both HTML and non-HTML text:

    var html = $.parseHTML('Hello world'); //parseHTML return HTMLCollection
    var text = $(html).text(); //use $() to get .text() method
    

    Plus parseHTML removes script tags completely which is useful as anti-hacking protection for user inputs.

    $('<p>Hello world</p><script>console.log(document.cookie)</script>').text();
    //returns "Hello worldconsole.log(document.cookie)"
    
    $($.parseHTML('<p>Hello world</p><script>console.log(document.cookie)</script>')).text();
    //returns "Hello world"
    
    0 讨论(0)
  • 2020-12-03 07:26

    Another option:

     $("<p>").html(myContent).text();
    
    0 讨论(0)
  • 2020-12-03 07:31

    I found in my specific case that I just needed to trim the content. Maybe not the answer asked in the question. But I thought I should add this answer anyway.

    $(myContent).text().trim()
    
    0 讨论(0)
  • 2020-12-03 07:35

    Could you not just try it?

    myContent = '<div id="test">Hello <span>world!</span></div>';
    console.log($(myContent).text()); //Prints "Hello world!"
    

    Note that you need to wrap the string in a jQuery object, otherwise it won't have a text method obviously.

    0 讨论(0)
提交回复
热议问题