HTML-encoding lost when attribute read from input field

前端 未结 25 3833
时光说笑
时光说笑 2020-11-21 04:04

I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.

For example,



        
25条回答
  •  被撕碎了的回忆
    2020-11-21 04:50

    Based on angular's sanitize... (es6 module syntax)

    // ref: https://github.com/angular/angular.js/blob/v1.3.14/src/ngSanitize/sanitize.js
    const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
    const NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
    
    const decodeElem = document.createElement('pre');
    
    
    /**
     * Decodes html encoded text, so that the actual string may
     * be used.
     * @param value
     * @returns {string} decoded text
     */
    export function decode(value) {
      if (!value) return '';
      decodeElem.innerHTML = value.replace(/ {
          var hi = value.charCodeAt(0);
          var low = value.charCodeAt(1);
          return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
        }).
        replace(NON_ALPHANUMERIC_REGEXP, value => {
          return '&#' + value.charCodeAt(0) + ';';
        }).
        replace(//g, '>');
    }
    
    export default {encode,decode};
    

提交回复
热议问题