簡體   English   中英

Javascript:對非HTML字符串使用Escape <>,但保留html

[英]Javascript: Escape <> for non-html strings, but preserve html

我有一些包含HTML的文本(將在瀏覽器中呈現),以及帶有<>任意字符串。 有沒有一種方法可以轉義那些任意標簽,但保留HTML? 如果有幫助,則將嚴格控制要解析的HTML,並且僅允許使用標簽的子集( bistrongbr

例如。 鑒於此文本:

<strong>Foobar</strong> <some other whatever>

我需要

<strong>Foobar</strong> &lt;some other whatever&gt;

一種便宜的選擇是將<>替換為占位符,然后在“良好”的上下文中恢復它們:

 allowedTags = ['strong', 'em', 'p']; text = '<strong>Foobar</strong> <some other whatever> <b>??</b> <em>hey</em>' text = text .replace(/</g, '\\x01') .replace(/>/g, '\\x02') .replace(new RegExp('\\x01(/?)(' + allowedTags.join('|') + ')\\x02', 'g'), "<$1$2>") .replace(/\\x01/g, '&lt;') .replace(/\\x02/g, '&gt;') console.log(text) 

不太便宜,但更正確的解決方案是使用(事件驅動)html解析器,並在進行操作時轉出不需要的內容。

暫無
暫無

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

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