我可以在 javascript 中转义 html 特殊字符吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6234773/
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
Can I escape html special chars in javascript?
提问by fernando123
I want to display a text to HTML by a javascript function. How can I escape html special chars in JS? Is there an API ?
我想通过 javascript 函数将文本显示为 HTML。如何在 JS 中转义 html 特殊字符?有 API 吗?
回答by bjornd
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
回答by spiderlama
function escapeHtml(html){
var text = document.createTextNode(html);
var p = document.createElement('p');
p.appendChild(text);
return p.innerHTML;
}
// Escape while typing & print result
document.querySelector('input').addEventListener('input', e => {
console.clear();
console.log( escapeHtml(e.target.value) );
});
<input style='width:90%; padding:6px;' placeholder='<b>cool</b>'>
回答by jeremysawesome
You can use jQuery's .text()
function.
您可以使用 jQuery 的.text()
函数。
For example:
例如:
From the jQuery documentation regarding the .text()
function:
从有关该.text()
功能的 jQuery 文档:
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML.
我们需要注意,此方法会根据需要对提供的字符串进行转义,以便在 HTML 中正确呈现。为此,它调用 DOM 方法 .createTextNode(),不会将字符串解释为 HTML。
Previous Versions of the jQuery Documentation worded it this way (emphasis added):
以前版本的 jQuery 文档是这样表述的(强调了添加):
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents(such as < for <).
我们需要注意,此方法会根据需要对提供的字符串进行转义,以便在 HTML 中正确呈现。为此,它调用 DOM 方法 .createTextNode(),该方法将特殊字符替换为其 HTML 实体等效项(例如 < for <)。
回答by cs01
回答by lvella
I think I found the proper way to do it...
我想我找到了正确的方法来做到这一点......
// Create a DOM Text node:
var text_node = document.createTextNode(unescaped_text);
// Get the HTML element where you want to insert the text into:
var elem = document.getElementById('msg_span');
// Optional: clear its old contents
//elem.innerHTML = '';
// Append the text node into it:
elem.appendChild(text_node);
回答by arjunpat
This is, by far, the fastest way I have seen it done. Plus, it does it all without adding, removing, or changing elements on the page.
到目前为止,这是我见过的最快的方法。此外,它无需添加、删除或更改页面上的元素即可完成所有操作。
function escapeHTML(unsafeText) {
let div = document.createElement('div');
div.innerText = unsafeText;
return div.innerHTML;
}
回答by iegik
It was interesting to find a better solution:
找到更好的解决方案很有趣:
var escapeHTML = function(unsafe) {
return unsafe.replace(/[&<"']/g, function(m) {
switch (m) {
case '&':
return '&';
case '<':
return '<';
case '"':
return '"';
default:
return ''';
}
});
};
I do not parse >
because it does not break XML/HTML code in the result.
我不解析,>
因为它不会破坏结果中的 XML/HTML 代码。
Here are the benchmarks: http://jsperf.com/regexpairsAlso, I created a universal escape
function: http://jsperf.com/regexpairs2
以下是基准测试:http: //jsperf.com/regexpairs另外,我创建了一个通用escape
函数:http: //jsperf.com/regexpairs2
回答by user
回答by teknopaul
DOM Elements support converting text to HTML by assigning to innerText. innerText is not a function but assigning to it works as if the text were escaped.
DOM 元素通过分配给innerText支持将文本转换为 HTML 。innerText 不是一个函数,但分配给它就像文本被转义一样工作。
document.querySelectorAll('#id')[0].innerText = 'unsafe " String >><>';
回答by Dave Brown
You can encode every character in your string:
您可以对字符串中的每个字符进行编码:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
Or just target the main characters to worry about (&, inebreaks, <, >, " and ') like:
或者只针对需要担心的主要角色 (&、inebreaks、<、>、" 和 '),例如:
function encode(r){
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
}
test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!');
/*************
* \x26 is &ersand (it has to be first),
* \x0A is newline,
*************/
<textarea id=test rows="9" cols="55">www.WHAK.com</textarea>