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


当前回答

const strip=(text) =>{
    return (new DOMParser()?.parseFromString(text,"text/html"))
    ?.body?.textContent
}

const value=document.getElementById("idOfEl").value

const cleanText=strip(value)

其他回答

myString.replace(/<[^>]*>?/gm, '');

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

对于转义字符,也可以使用模式匹配:

myString.replace(/((&lt)|(<)(?:.|\n)*?(&gt)|(>))/gm, '');

大多数情况下,接受的答案都很好,但是在IE中,如果html字符串为空,则会得到“null”(而不是“”)。固定的:

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

使用jQuery,您可以使用

$('#elementID').text()