zoukankan      html  css  js  c++  java
  • Does javascript have an Equivalent to C#s HttpUtility.HtmlEncode? [duplicate]

    Does javascript have an Equivalent to C#s HttpUtility.HtmlEncode? [duplicate]

    HTML-encoding lost when attribute read from input field

    回答1

    EDIT: This answer was posted a long ago, and the htmlDecode function introduced a XSS vulnerability. It has been modified changing the temporary element from a div to a textarea reducing the XSS chance. But nowadays, I would encourage you to use the DOMParser API as suggested in other anwswer.


    I use these functions:

    function htmlEncode(value){
      // Create a in-memory element, set its inner text (which is automatically encoded)
      // Then grab the encoded contents back out. The element never exists on the DOM.
      return $('<textarea/>').text(value).html();
    }
    
    function htmlDecode(value){
      return $('<textarea/>').html(value).text();
    }
    

    Basically a textarea element is created in memory, but it is never appended to the document.

    On the htmlEncode function I set the innerText of the element, and retrieve the encoded innerHTML; on the htmlDecode function I set the innerHTML value of the element and the innerText is retrieved.

    Check a running example here.

    回答2

    Here's a non-jQuery version that is considerably faster than both the jQuery .html() version and the .replace() version. This preserves all whitespace, but like the jQuery version, doesn't handle quotes.

    function htmlEncode( html ) {
        return document.createElement( 'a' ).appendChild( 
            document.createTextNode( html ) ).parentNode.innerHTML;
    };
    

    Script:

    function htmlEncode( html ) {
        return document.createElement( 'a' ).appendChild( 
            document.createTextNode( html ) ).parentNode.innerHTML;
    };
    
    function htmlDecode( html ) {
        var a = document.createElement( 'a' ); a.innerHTML = html;
        return a.textContent;
    };
    
    document.getElementById( 'text' ).value = htmlEncode( document.getElementById( 'hidden' ).value );
    
    //sanity check
    var html = '<div>   &amp; hello</div>';
    document.getElementById( 'same' ).textContent = 
          'html === htmlDecode( htmlEncode( html ) ): ' 
        + ( html === htmlDecode( htmlEncode( html ) ) );
    

    HTML:

    <input id="hidden" type="hidden" value="chalk    &amp; cheese" />
    <input id="text" value="" />
    <div id="same"></div>
    
  • 相关阅读:
    移动端前端布局的必看前提
    单词统计
    用户场景分析
    学习进度(九)
    团队项目
    学习进度(二)
    数据可视化
    大二下,学习进度(一)
    求最大子数组的和
    构建之法3
  • 原文地址:https://www.cnblogs.com/chucklu/p/15305031.html
Copyright © 2011-2022 走看看