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


当前回答

方法1:

function cleanHTML(str){
  str.replace(/<(?<=<)(.*?)(?=>)>/g, '&lt;$1&gt;');
}

function uncleanHTML(str){
  str.replace(/&lt;(?<=&lt;)(.*?)(?=&gt;)&gt;/g, '<$1>');
}

方法2:

function cleanHTML(str){
  str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function uncleanHTML(str){
  str.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}

此外,不要忘记,如果用户碰巧发布了一条数学评论(例如:1<2),您不想删除整个评论。浏览器(仅测试了chrome)不将unicode作为html标记运行。如果将所有<替换为&lt;字符串中的每一个文件,unicode都将显示<为文本,而不运行任何html。我推荐方法2。jquery也能很好地工作$('#element').text();

其他回答

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

var div = document.getElementsByTagName('div');
for (var i=0; i<div.length; i++) {
    div[i].insertAdjacentHTML('afterend', div[i].innerHTML);
    document.body.removeChild(div[i]);
}

简单的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

我认为最简单的方法就是像上面提到的那样使用正则表达式。虽然没有理由使用一堆。尝试:

stringWithHTML = stringWithHTML.replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, "");

使用jQuery,您可以使用

$('#elementID').text()

我对Jibberboy 2000的原始脚本做了一些修改希望对某人有用

str = '**ANY HTML CONTENT HERE**';

str=str.replace(/<\s*br\/*>/gi, "\n");
str=str.replace(/<\s*a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 (Link->$1) ");
str=str.replace(/<\s*\/*.+?>/ig, "\n");
str=str.replace(/ {2,}/gi, " ");
str=str.replace(/\n+\s*/gi, "\n\n");