英文:
Encode html variable using react
问题
我有一个包含HTML字符的变量。这个变量必须转换为HTML安全字符串。我应该怎么做?
示例:
data.X = ""<img src='abc'>"";
//data.X = magicEncoder(data.X)
//经过magicEncoder处理后的data.X内容:
&lt;img&nbsp;src=&#39;abc&#39;&gt;
我尝试过查找domPurify但没有成功,只是它剥离了HTML而不是对内容进行编码。
英文:
I have a variable that contains html characters. This variable must be converted to an html safe string. How do I do this?
Example:
data.X="<img src='abc'>";
//data.X=magicEncoder(data.X)
//Contents of data.X after magicEncoder:
&lt;img&nbsp;src=&#39;abc&#39;&gt;
I have tried looking up domPurify without success only to have it strip the html instead of encoding the contents.
答案1
得分: 1
你是否尝试过使用一个叫做:he (HTML实体) 的库?
在你的示例中,可能会像这样:
data.X = ""<img src='abc'>"";
const encodedString = he.encode(data.X);
console.log(encodedString);
这将给你:&lt;img src=&#x27;abc&#x27;&gt;
让我知道进展如何 - 我自己没有使用过这个,但似乎是一个不错的方法。这里还有另一个答案提供的更多信息:什么是解码具有特殊HTML实体的字符串的正确方法。
英文:
Have you tried using a library called: he (HTML Entities?
In your example it might look like:
data.X = "<img src='abc'>";
const encodedString = he.encode(data.X);
console.log(encodedString);
which gives you: &lt;img src=&#x27;abc&#x27;&gt;
Let me know how it goes - I haven't used this myself but seems to be a good way to do it. Here's more info from another answer: Whats the right way to decode a string that has special html entities in it
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论