js过滤文本中html标签的两种方法.

 

方法一:innerHTML方法

具体实现代码如下:

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

使用方法:

strip(\"<div><a href=\'http://www.manongjc.com\'>码农教程</a></div>\")

 

方法二:正则表达式

代码如下:

< >

  stripHtml(\"<div><a href=\'http://www.manongjc.com\'>码农教程</a></div>\");
 
  
function stripHtml(str) {
  // Remove some tags
  str = str.replace(/<[^>]+>/gim, \'\');

  // Remove BB code
  str = str.replace(/\\[(\\w+)[^\\]]*](.*?)\\[\\/\\1]/g, \'$2 \');

  // Remove html and line breaks
  const div = document.createElement(\'div\');
  div.innerHTML = str;

  const input = document.createElement(\'input\');
  input.value = div.textContent || div.innerText || \'\';

  alert(input.value);
}
</ >
收藏 打印