![](/img/trans.png)
[英]How can I sanitize and convert characters to HTML entities while preserving HTML tags (Javascript/NodeJS)?
[英]Convert tags to html entities
是否可以使用javascript / jquery使用任何可能的方式(如正则表达式或其他方式)将html标签转换为html实体。 如果是,那怎么样?
例:
<div>
应转换为<div>
注意:我不是在谈论服务器端语言。
对HTML特殊字符尝试此函数:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
当您使用jquery标记时,基于jQuery的解决方案应该适合您:
$("<div>").text("<div>bleh</div>whatever").html()
将参数替换为text-method,使用您要转义的标记。
我有2个安全编码HTML的快速和小型实现。
您可以对字符串中的所有字符进行编码:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
或者只是针对主角担心(&,inebreaks,<,>,“和'),如:
function encode(r){ return r.replace(/[\\x26\\x0A\\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"}) } var myString='Encode HTML entities!\\n"Safe" escape <script></'+'script> & other tags!'; test.value=encode(myString); testing.innerHTML=encode(myString); /************* * \\x26 is &ersand (it has to be first), * \\x0A is newline, *************/
<p><b>What JavaScript Generated:</b></p> <textarea id=test rows="3" cols="55"></textarea> <p><b>What It Renders Too In HTML:</b></p> <div id="testing">www.WHAK.com</div>
在JQuery中:
$('<div/>').text('This is fun & stuff').html(); // evaluates to "This is fun & stuff"
http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
如果您有变量并且想要将其插入div,则可以调用text()。
var myVar = "<span><strong>Some vars</strong> Some var extra</span>";
$("div").text(myVar);
var d = "<div>"
d = d.replace(/<|>/g, function(chr){
return chr == "<" ? "<" : ">"
})
console.log(d)
使用String.prototype.replace()
和正则表达式有一个简洁的方法,如下所示:
var tag = "<h1>This should </h1>be bold<h2> and big</h2>";
var escapedTag = tag.replace(/</g, "<").replace(/>/g, ">");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.