Strip HTML from Text JavaScript

2018-12-31 00:39发布

Is there an easy way to take a string of html in JavaScript and strip out the html?

30条回答
牵手、夕阳
2楼-- · 2018-12-31 00:50

If you're running in a browser, then the easiest way is just to let the browser do it for you...

function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent || tmp.innerText || "";
}

Note: as folks have noted in the comments, this is best avoided if you don't control the source of the HTML (for example, don't run this on anything that could've come from user input). For those scenarios, you can still let the browser do the work for you - see Saba's answer on using the now widely-available DOMParser.

查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 00:51

Simplest way:

jQuery(html).text();

That retrieves all the text from a string of html.

查看更多
步步皆殇っ
4楼-- · 2018-12-31 00:51

As an extension to the jQuery method, if your string might not contian HTML (eg if you are trying to remove HTML from a form field)

jQuery(html).text();

will return an empty string if there is no html

Use:

jQuery('<p>' + html + '</p>').text();

instead.

Update: As has been pointed out in the comments, in some circumstances this solution will execute javascript contained within html if the value of html could be influenced by an attacker, use a different solution.

查看更多
妖精总统
5楼-- · 2018-12-31 00:51

After trying all of the answers mentioned most if not all of them had edge cases and couldn't completely support my needs.

I started exploring how php does it and came across the php.js lib which replicates the strip_tags method here: http://phpjs.org/functions/strip_tags/

查看更多
查无此人
6楼-- · 2018-12-31 00:51

Using Jquery:

function stripTags() {
    return $('<p></p>').html(textToEscape).text()
}
查看更多
心情的温度
7楼-- · 2018-12-31 00:52

Another, admittedly less elegant solution than nickf's or Shog9's, would be to recursively walk the DOM starting at the <body> tag and append each text node.

var bodyContent = document.getElementsByTagName('body')[0];
var result = appendTextNodes(bodyContent);

function appendTextNodes(element) {
    var text = '';

    // Loop through the childNodes of the passed in element
    for (var i = 0, len = element.childNodes.length; i < len; i++) {
        // Get a reference to the current child
        var node = element.childNodes[i];
        // Append the node's value if it's a text node
        if (node.nodeType == 3) {
            text += node.nodeValue;
        }
        // Recurse through the node's children, if there are any
        if (node.childNodes.length > 0) {
            appendTextNodes(node);
        }
    }
    // Return the final result
    return text;
}
查看更多
登录 后发表回答