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>
    
  • 相关阅读:
    Python引入pandas报错ValueError: numpy.ufunc has the wrong size, try recompiling
    Oracle TNS无法解析ORA-12154报错
    python两个一维list列表合并
    SQL数据表加索引CREATE INDEX
    Python 格式化输出
    Python中三个双引号的作用
    2.认识素描
    如何快速学习Tableau Desktop
    1.怎样学习素描
    正点原子嵌入式Linux笔记3——Ubuntu软件安装
  • 原文地址:https://www.cnblogs.com/chucklu/p/15305031.html
Copyright © 2011-2022 走看看