Strip HTML from Text JavaScript

前端 未结 30 3572
北荒
北荒 2020-11-21 05:08

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

30条回答
  •  死守一世寂寞
    2020-11-21 05:40

    Another, admittedly less elegant solution than nickf's or Shog9's, would be to recursively walk the DOM starting at the 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;
    }
    

提交回复
热议问题