簡體   English   中英

從來自服務器的字符串中刪除HTML標簽和實體

[英]Remove HTML tags and entites from string coming from server

在一個應用程序中,我收到一些HTML文本:由於該應用程序無法顯示(解釋)HTML,因此我需要從從服務器接收的字符串中刪除任何HTML標記和實體。

我嘗試了以下操作,但是此操作刪除了HTML標簽,但未刪除實體(例如&bnsp;):

stringFromServer.replace(/(<([^>]+)>)/ig,"");

任何幫助表示贊賞。

免責聲明:我需要一個純JavaScript解決方案(沒有JQuery,Underscore等)。

[更新] 我現在正在閱讀所有答案,而我忘了提及我使用的是JavaScript,但環境不是網頁,因此我沒有DOM

您可以嘗試如下操作:

var placeholder = document.createElement('div');
placeholder.innerHTML = stringFromServer;

var theText = placeholder.innerText;

.innerText僅從元素中獲取文本內容。

但是,由於看上去您根本無法訪問任何DOM操作,因此您可能將不得不使用某種HTML解析器,例如:
https://www.npmjs.org/package/htmlparser
http://ejohn.org/blog/pure-javascript-html-parser/

在Mozilla的MDN上可以找到不使用正則表達式或幻影div的解決方案。

我將代碼放在這里JSfiddle中

var sMyString = "<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>";
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(sMyString, "text/xml");
// print the name of the root element or error message
alert(oDOM.documentElement.nodeName == "parsererror" ?
       "error while parsing" : oDOM.documentElement.textContent);

或者,解析新文檔中的HTML代碼段,然后從中進行dom操作(如果您希望將其與當前文檔分開):

var tmpDoc=document.implementation.createHTMLDocument("");
tmpDoc.body.innerHTML="<a href='#'>some text</a><p style=''> more text</p>";
tmpDoc.body.textContent;

tmpDoc.body.textContent計算為:

some text more text
stringFromServer.replace(/(<([^>]+)>|&[^;]+;)/ig, "")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM