[英]Convert tags to html entities
Is it possible to convert html tags to html entities using javascript/jquery using any way possible such as regex or some other way. 是否可以使用javascript / jquery使用任何可能的方式(如正则表达式或其他方式)将html标签转换为html实体。 If yes, then how?
如果是,那怎么样?
Example: 例:
<div>
should be converted to <div>
<div>
应转换为<div>
Note: I am not talking about server-side languages. 注意:我不是在谈论服务器端语言。
Try this function for the HTML special characters: 对HTML特殊字符尝试此函数:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
As you tagged with jquery, a jQuery-powered solution should work for you: 当您使用jquery标记时,基于jQuery的解决方案应该适合您:
$("<div>").text("<div>bleh</div>whatever").html()
Replace the argument to the text-method with whatever markup you want to escape. 将参数替换为text-method,使用您要转义的标记。
I have 2 fast and small implementations for encoding HTML safely. 我有2个安全编码HTML的快速和小型实现。
You can encode all characters 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)+";"}) } 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>
In JQuery: 在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 http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
If you have the variable and you want to insert it on a div, you can call text(). 如果您有变量并且想要将其插入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)
There's a concise way of doing this using String.prototype.replace()
and regular expressions as follows: 使用
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.