簡體   English   中英

從字符串中刪除HTML

[英]Removing HTML from a string

我有一張桌子(Wijmo網格)。 日志列中包含一些文本。

允許用戶在文本中編寫HTML ,因為郵寄時也會使用相同的文本,以使其外觀漂亮且樣式精美。

假設文字為:

var text = "Hello friend <br> How are you? <h1> from me </h1>";

我可以/應該使用任何方法或JSON.stringify()和HTML.enocde()來獲取:

var textWithoutHtml = magic(text); // "Hello friend How are you? from me"

問題之一是,如果文本包含"<br>"則它會折斷到表格行的下一行,並且有可能看到該行第二行的上半部分,但女巫看起來不太好。

var text = "Hello friend <br> How are you? <h1> from me </h1>";
var newText = text.replace(/(<([^>]+)>)/ig, "");

小提琴: http//jsfiddle.net/EfRs6/

您可以這樣嘗試:

string s = Regex.Replace("Hello friend <br> How are you? <h1> from me </h1>", @"<[^>]+>|&nbsp;", "").Trim();

您還可以檢查HTML Agility Pack

這是一個敏捷的HTML解析器,它構建了一個讀/寫DOM並支持純XPATH或XSLT(您實際上不必了解XPATH或XSLT來使用它,不用擔心...)。 這是一個.NET代碼庫,可讓您解析“網絡外” HTML文件。 該解析器對“真實世界”格式的HTML十分寬容。 對象模型與提出System.Xml的對象模型非常相似,但用於HTML文檔(或流)。

<[^>]+>|&nbsp;/
1st Alternative: <[^>]+>
< matches the characters < literally
[^>]+ match a single character not present in the list below
Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
> a single character in the list > literally (case sensitive)
> matches the characters > literally
2nd Alternative: &nbsp;
&nbsp; matches the characters &nbsp; literally (case sensitive)

據我了解您的問題,您可以在C#中編碼這樣的值

string encodedValue= HttpUtility.HtmlEncode(txtInput.Text);

注意:此處txtInput是頁面上TextBox的ID。

暫無
暫無

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

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