Convert HTML Character Entities back to regular text using javascript

后端 未结 5 2060
梦毁少年i
梦毁少年i 2020-11-29 08:54

the questions says it all :)

eg. we have >, we need > using only javascript

Update: It seems jquery is t

5条回答
  •  眼角桃花
    2020-11-29 09:03

    You could do something like this:

    String.prototype.decodeHTML = function() {
        var map = {"gt":">" /* , … */};
        return this.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);?/gi, function($0, $1) {
            if ($1[0] === "#") {
                return String.fromCharCode($1[1].toLowerCase() === "x" ? parseInt($1.substr(2), 16)  : parseInt($1.substr(1), 10));
            } else {
                return map.hasOwnProperty($1) ? map[$1] : $0;
            }
        });
    };
    

提交回复
热议问题