如何在 JavaScript 中编码字符串以在 HTML 中显示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14129953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to encode a string in JavaScript for displaying in HTML?
提问by James
Possible Duplicate:
How to escape HTML
可能的重复:
如何转义 HTML
How can a string be converted to HTML in JavaScript?
如何在 JavaScript 中将字符串转换为 HTML?
e.g.
例如
var unsafestring = "<oohlook&atme>";
var safestring = magic(unsafestring);
where safestringnow equals "<ohhlook&atme>"
其中,safestring现在等于"<ohhlook&atme>"
I am looking for magic(...).
I am not using JQuery for magic.
我正在寻找magic(...). 我没有将 JQuery 用于magic.
回答by j08691
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
So then with var unsafestring = "<oohlook&atme>";you would use htmlEntities(unsafestring);
那么var unsafestring = "<oohlook&atme>";你会使用htmlEntities(unsafestring);
回答by gdoron is supporting Monica
If you want to use a library rather than doing it yourself:
如果你想使用图书馆而不是自己做:
The most commonly used way is using jQuery for this purpose:
为此,最常用的方法是使用 jQuery:
var safestring = $('<div>').text(unsafestring).html();
If you want to to encode all the HTML entities you will have to use a library or write it yourself.
如果要对所有 HTML 实体进行编码,则必须使用库或自己编写。
You can use a more compact library than jQuery, like HTML Encoder and Decode
你可以使用比 jQuery 更紧凑的库,比如HTML Encoder 和 Decode
回答by Oleg V. Volkov
Do not bother with encoding. Use a text node instead. Data in text node is guaranteed to be treated as text.
不要打扰编码。请改用文本节点。文本节点中的数据保证被视为文本。
document.body.appendChild(document.createTextNode("Your&funky<text>here"))
回答by ThiefMaster
You need to escape <and &. Escaping >too doesn't hurt:
你需要逃脱<和&。逃跑>也无伤大雅:
function magic(input) {
input = input.replace(/&/g, '&');
input = input.replace(/</g, '<');
input = input.replace(/>/g, '>');
return input;
}
Or you let the DOM engine do the dirty work for you (using jQuery because I'm lazy):
或者你让 DOM 引擎为你做脏活(使用 jQuery,因为我很懒):
function magic(input) {
return $('<span>').text(input).html();
}
What this does is creating a dummy element, assigning your string as its textContent(i.e. no HTML-specific characters have side effects since it's just text) and then you retrieve the HTML content of that element - which is the text but with special characters converted to HTML entities in cases where it's necessary.
这样做是创建一个虚拟元素,将您的字符串分配为其textContent(即没有特定于 HTML 的字符具有副作用,因为它只是文本),然后您检索该元素的 HTML 内容 - 这是文本,但转换了特殊字符在必要的情况下到 HTML 实体。
回答by Niet the Dark Absol
The only character that needs escaping is <. (>is meaningless outside of a tag).
唯一需要转义的字符是<. (>在标签之外是无意义的)。
Therefore, your "magic" code is:
因此,您的“魔术”代码是:
safestring = unsafestring.replace(/</g,'<');

