HTML-encoding lost when attribute read from input field

前端 未结 25 3910
时光说笑
时光说笑 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 05:09

    Using some of the other answers here I made a version that replaces all the pertinent characters in one pass irrespective of the number of distinct encoded characters (only one call to replace()) so will be faster for larger strings.

    It doesn't rely on the DOM API to exist or on other libraries.

    window.encodeHTML = (function() {
        function escapeRegex(s) {
            return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
        }
        var encodings = {
            '&'  : '&',
            '"'  : '"',
            '\'' : ''',
            '<'  : '&lt;',
            '>'  : '&gt;',
            '\\' : '&#x2F;'
        };
        function encode(what) { return encodings[what]; };
        var specialChars = new RegExp('[' +
            escapeRegex(Object.keys(encodings).join('')) +
        ']', 'g');
    
        return function(text) { return text.replace(specialChars, encode); };
    })();
    

    Having ran that once, you can now call

    encodeHTML('<>&"\'')
    

    To get &lt;&gt;&amp;&quot;&#39;

    0 讨论(0)
提交回复
热议问题