将标签转换为html实体

时间:2010-04-10 13:42:28

标签: javascript jquery html regex

是否可以使用javascript / jquery以任何可能的方式将html标签转换为html实体,例如正则表达式或其他方式。如果是,那怎么办?

示例:

<div>应转换为&lt;div&gt;

注意:我不是在谈论服务器端语言。

7 个答案:

答案 0 :(得分:28)

对HTML特殊字符尝试此函数:

function htmlencode(str) {
    return str.replace(/[&<>"']/g, function($0) {
        return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
    });
}

答案 1 :(得分:8)

当您使用jquery标记时,基于jQuery的解决方案应该适合您:

$("<div>").text("<div>bleh</div>whatever").html()

将参数替换为text-method,使用您想要转义的任何标记。

答案 2 :(得分:2)

我有2个安全编码HTML的快速和小型实现。

您可以对字符串中的所有字符进行编码:

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

或者只是针对主角担心(&amp;,inebreaks,&lt;,&gt;,&#34;和&#39;),如:

&#13;
&#13;
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 &ampersand (it has to be first),
* \x0A is newline,
*************/
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

在JQuery中:

$('<div/>').text('This is fun & stuff').html(); // evaluates to "This is fun &amp; stuff"

http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb

答案 4 :(得分:1)

如果您有变量并且想要将其插入div,则可以调用text()。

var myVar = "<span><strong>Some vars</strong> Some var extra</span>";
$("div").text(myVar);

答案 5 :(得分:0)

var d = "<div>"
d = d.replace(/<|>/g, function(chr){
    return chr == "<" ? "&lt;" : "&gt;"
})
console.log(d)

答案 6 :(得分:0)

使用String.prototype.replace()和正则表达式执行此操作的简洁方法如下:

var tag = "<h1>This should </h1>be bold<h2> and big</h2>";
var escapedTag = tag.replace(/</g, "&lt;").replace(/>/g, "&gt;");