簡體   English   中英

從字符串中替換所有出現的html標記和特殊的unicode字符

[英]Replace all occurrences of html tags and special unicode character from a string

我有一些像這樣的文字

Keeping up with friends is faster than ever.<p>&#x2022; See what friends are up to<br>&#x2022; Share updates, photos and videos<br>&#x2022;

我想要這樣的文字

Keeping up with friends is faster than ever.
 • See what friends are up to
 • Share updates, photos and videos

我通過str.replace(/<[^>]+>/gm, '')清除了html標簽,但是我無法刪除特殊符號。

我正在計算字符串的長度,所以在瀏覽器編譯之前特殊字符給了我不同的長度。

謝謝

在這種情況下,最好使用外部庫(如jQuery)來幫助您。

在下面的示例中,我使用名為text()的jQuery函數。 這是文檔: http//api.jquery.com/text/

顧名思義,jQuery文本函數將HTML作為文本讀取。

 var asText = $("#example").text(); $("#asText").text(asText); $("#asTextLength").text(asText.length); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <p id="example">&#x2022; Ex<em>ample</em> &amp; <span>T<strong>est</strong></span></p> <p id="asText"></p> <p id="asTextLength"></p> 

執行此操作的唯一“正確”(完整)方法是將文檔解析為HTML DOM,然后創建將讀取DOM並將其格式化為“簡單”定義的內容。

有許多工具可以在Javascript之外執行此操作,之前的StackOverflow交換討論了其中一些:

我認為在Javascript中“滾動你自己”將是痛苦的,除非你設置了非常低的標准,並且只努力“非常化”非常有限的HTML。

話雖這么說,為什么你不能繼續使用你所擁有的一個工具,並繼續加入“規則”來處理你想要處理的東西?

str.replace(/&#x2022;/gm, '•')

等等,yada yada yada, ad nauseum ...

你可以使用ng-bind-html例如

<p ng-bind-html="myHTML"></p>

$scope.myHTML = 'Keeping up with friends is faster than ever.<p>&#x2022; See what friends are up to<br>&#x2022; Share updates, photos and videos<br>&#x2022;';

暫無
暫無

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

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