代码之家  ›  专栏  ›  技术社区  ›  Sarfraz

将标记转换为html实体

  •  11
  • Sarfraz  · 技术社区  · 14 年前

    例子:

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

    我不是在说服务器端语言。

    7 回复  |  直到 14 年前
        1
  •  29
  •   Gumbo    14 年前

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

    function htmlencode(str) {
        return str.replace(/[&<>"']/g, function($0) {
            return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
        });
    }
    
        2
  •  8
  •   Jörn Zaefferer    14 年前

    正如您使用jquery标记的那样,jquery支持的解决方案应该适合您:

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

        3
  •  2
  •   Dave Brown    9 年前

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

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

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

    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,
    *************/
    <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>
        4
  •  1
  •   riotera    14 年前

    在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

        5
  •  1
  •   metrobalderas    14 年前

    var myVar = "<span><strong>Some vars</strong> Some var extra</span>";
    $("div").text(myVar);
    
        6
  •  0
  •   mwilcox    14 年前
    var d = "<div>"
    d = d.replace(/<|>/g, function(chr){
        return chr == "<" ? "&lt;" : "&gt;"
    })
    console.log(d)
    
        7
  •  0
  •   software_writer    8 年前

    有一种简洁的方法可以使用 String.prototype.replace()

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