有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?


当前回答

另一个公认不如nickf或Shog9优雅的解决方案是从<body>标记开始递归遍历DOM并附加每个文本节点。

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;
}

其他回答

如果你在浏览器中运行,那么最简单的方法就是让浏览器为你做。。。

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

注意:正如人们在评论中所指出的,如果您不控制HTML的源代码(例如,不要在可能来自用户输入的任何内容上运行此代码),最好避免这种情况。对于这些场景,您仍然可以让浏览器为您完成工作-请参阅Saba关于使用现在广泛可用的DOMParser的回答。

对公认答案的改进。

function strip(html)
{
   var tmp = document.implementation.createHTMLDocument("New").body;
   tmp.innerHTML = html;
   return tmp.textContent || tmp.innerText || "";
}

这样一来,像这样运行的东西不会造成任何伤害:

strip("<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>")

Firefox、Chromium和Explorer 9+是安全的。歌剧院普雷斯托仍然很脆弱。字符串中提到的图像也不会在Chromium和Firefox中保存http请求。

您可以使用以下正则表达式去掉所有html标记:/<(.|\n)*?>/克

例子:

let str = "<font class=\"ClsName\">int[0]</font><font class=\"StrLit\">()</font>";
console.log(str.replace(/<(.|\n)*?>/g, ''));

输出:

int[0]()
var STR='<Your HTML STRING>''
var HTMLParsedText="";
   var resultSet =  STR.split('>')
   var resultSetLength =resultSet.length
   var counter=0
   while(resultSetLength>0)
   {
      if(resultSet[counter].indexOf('<')>0)
      {    
        var value = resultSet[counter];
        value=value.substring(0, resultSet[counter].indexOf('<'))
        if (resultSet[counter].indexOf('&')>=0 && resultSet[counter].indexOf(';')>=0) {
            value=value.replace(value.substring(resultSet[counter].indexOf('&'), resultSet[counter].indexOf(';')+1),'')
        }
      }
        if (value)
        {
          value = value.trim();
          if(HTMLParsedText === "")
          {
              HTMLParsedText = value;
          }
          else
          {
            if (value) {
              HTMLParsedText = HTMLParsedText + "\n" + value;
            }
          }
          value='';
        }
        counter= counter+1;
      resultSetLength=resultSetLength-1;
   }
  console.log(HTMLParsedText);

简单的2行jquery去掉html。

 var content = "<p>checking the html source&nbsp;</p><p>&nbsp;
  </p><p>with&nbsp;</p><p>all</p><p>the html&nbsp;</p><p>content</p>";

 var text = $(content).text();//It gets you the plain text
 console.log(text);//check the data in your console

 cj("#text_area_id").val(text);//set your content to text area using text_area_id