Convert tags to html entities

后端 未结 7 690
小蘑菇
小蘑菇 2020-12-08 17:16

Is it possible to convert html tags to html entities using javascript/jquery using any way possible such as regex or some other way. If yes, then how?

Exampl

相关标签:
7条回答
  • 2020-12-08 17:36

    In 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

    0 讨论(0)
  • 2020-12-08 17:40

    There's a concise way of doing this using String.prototype.replace() and regular expressions as follows:

    var tag = "<h1>This should </h1>be bold<h2> and big</h2>";
    var escapedTag = tag.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    
    0 讨论(0)
  • 2020-12-08 17:43

    If you have the variable and you want to insert it on a div, you can call text().

    var myVar = "<span><strong>Some vars</strong> Some var extra</span>";
    $("div").text(myVar);
    
    0 讨论(0)
  • 2020-12-08 17:44

    As you tagged with jquery, a jQuery-powered solution should work for you:

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

    Replace the argument to the text-method with whatever markup you want to escape.

    0 讨论(0)
  • 2020-12-08 17:50
    var d = "<div>"
    d = d.replace(/<|>/g, function(chr){
        return chr == "<" ? "&lt;" : "&gt;"
    })
    console.log(d)
    
    0 讨论(0)
  • 2020-12-08 17:54

    I have 2 fast and small implementations for encoding HTML safely.

    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:

    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>

    0 讨论(0)
提交回复
热议问题