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>
    
  • 相关阅读:
    mysql/oracle 小技巧自动插入当前时间
    Java StringUtil 用法示例
    timestamp与String的相互转换
    gzip/gunzip用法
    maven常用指令
    微基站、宏基站区别
    CRAN方案
    让gvim中支持utf8编辑
    java正则表达式的几个小例子
    Sql Server数据库汉字按字母、笔划、拼音首字母、排序
  • 原文地址:https://www.cnblogs.com/chucklu/p/15305031.html
Copyright © 2011-2022 走看看