How to decode HTML entities using jQuery?

后端 未结 19 2206
忘了有多久
忘了有多久 2020-11-21 23:21

How do I use jQuery to decode HTML entities in a string?

相关标签:
19条回答
  • 2020-11-21 23:43

    I just had to have an HTML entity charater (⇓) as a value for a HTML button. The HTML code looks good from the beginning in the browser:

    <input type="button" value="Embed & Share  &dArr;" id="share_button" />
    

    Now I was adding a toggle that should also display the charater. This is my solution

    $("#share_button").toggle(
        function(){
            $("#share").slideDown();
            $(this).attr("value", "Embed & Share " + $("<div>").html("&uArr;").text());
        }
    

    This displays ⇓ again in the button. I hope this might help someone.

    0 讨论(0)
  • 2020-11-21 23:46

    For ExtJS users, if you already have the encoded string, for example when the returned value of a library function is the innerHTML content, consider this ExtJS function:

    Ext.util.Format.htmlDecode(innerHtmlContent)
    
    0 讨论(0)
  • 2020-11-21 23:50

    Like Mike Samuel said, don't use jQuery.html().text() to decode html entities as it's unsafe.

    Instead, use a template renderer like Mustache.js or decodeEntities from @VyvIT's comment.

    Underscore.js utility-belt library comes with escape and unescape methods, but they are not safe for user input:

    _.escape(string)

    _.unescape(string)

    0 讨论(0)
  • 2020-11-21 23:50

    Extend a String class:

    String::decode = ->
      $('<textarea />').html(this).text()
    

    and use as method:

    "&lt;img src='myimage.jpg'&gt;".decode()
    
    0 讨论(0)
  • 2020-11-21 23:52

    Here are still one problem: Escaped string does not look readable when assigned to input value

    var string = _.escape("<img src=fake onerror=alert('boo!')>");
    $('input').val(string);
    

    Exapmle: https://jsfiddle.net/kjpdwmqa/3/

    0 讨论(0)
  • 2020-11-21 23:55

    The question is limited by 'with jQuery' but it might help some to know that the jQuery code given in the best answer here does the following underneath...this works with or without jQuery:

    function decodeEntities(input) {
      var y = document.createElement('textarea');
      y.innerHTML = input;
      return y.value;
    }
    
    0 讨论(0)
提交回复
热议问题