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

后端 未结 6 1911
不思量自难忘°
不思量自难忘° 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: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.

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

    You must either wrap the text in valid HTML:

    $('
    ' + 'Hello world' + '
    ').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.

    $('

    Hello world

    ').text(); //returns "Hello worldconsole.log(document.cookie)" $($.parseHTML('

    Hello world

    ')).text(); //returns "Hello world"

提交回复
热议问题