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>
    
  • 相关阅读:
    vue+element实现图片上传
    react----Hooks的基本使用
    js知识点大杂烩
    vue面试题(一)
    从一个字符串中找出重复次数最多的字符?
    百度搜索
    js--拖拽
    js循环嵌套,打印图形
    js--sort()排序
    闰秒调整扫盲
  • 原文地址:https://www.cnblogs.com/chucklu/p/15305031.html
Copyright © 2011-2022 走看看