Unescape HTML entities in Javascript?

前端 未结 30 2996
野趣味
野趣味 2020-11-21 05:40

I have some Javascript code that communicates with an XML-RPC backend. The XML-RPC returns strings of the form:


30条回答
  •  暖寄归人
    2020-11-21 05:57

    You're welcome...just a messenger...full credit goes to ourcodeworld.com, link below.

    window.htmlentities = {
            /**
             * Converts a string to its html characters completely.
             *
             * @param {String} str String with unescaped HTML characters
             **/
            encode : function(str) {
                var buf = [];
    
                for (var i=str.length-1;i>=0;i--) {
                    buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
                }
    
                return buf.join('');
            },
            /**
             * Converts an html characterSet into its original character.
             *
             * @param {String} str htmlSet entities
             **/
            decode : function(str) {
                return str.replace(/&#(\d+);/g, function(match, dec) {
                    return String.fromCharCode(dec);
                });
            }
        };
    

    Full Credit: https://ourcodeworld.com/articles/read/188/encode-and-decode-html-entities-using-pure-javascript

提交回复
热议问题