我如何编码和解码HTML实体使用JavaScript或JQuery?

var varTitle = "Chris' corner";

我希望它是:

var varTitle = "Chris' corner";

当前回答

jQuery提供了一种编码和解码html实体的方法。

如果你使用"<div/>"标签,它会删除所有的html。

function htmlDecode(value) {
    return $("<div/>").html(value).text();
}

function htmlEncode(value) {
    return $('<div/>').text(value).html();
}

如果你使用"<textarea/>"标签,它将保留html标签。

function htmlDecode(value) {
    return $("<textarea/>").html(value).text();
}

function htmlEncode(value) {
    return $('<textarea/>').text(value).html();
}

其他回答

受Robert K的解决方案的启发,这个版本不剥离HTML标记,而且同样安全。

var decode_entities = (function() {
    // Remove HTML Entities
    var element = document.createElement('div');

    function decode_HTML_entities (str) {

        if(str && typeof str === 'string') {

            // Escape HTML before decoding for HTML Entities
            str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';');

            element.innerHTML = str;
            if(element.innerText){
                str = element.innerText;
                element.innerText = '';
            }else{
                // Firefox support
                str = element.textContent;
                element.textContent = '';
            }
        }
        return unescape(str);
    }
    return decode_HTML_entities;
})();

向页面中注入不受信任的HTML是危险的,如如何使用jQuery解码HTML实体中所述。

一种替代方法是使用PHP html_entity_decode的纯javascript实现(来自http://phpjs.org/functions/html_entity_decode:424)。这个例子应该是这样的:

var varTitle = html_entity_decode("Chris&apos; corner");

你可以尝试这样做:

var Title = $('<textarea />').html("Chris&apos;角”)。text (); console.log(标题); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>

J.S.小提琴。

更具互动性的版本:

$('form').submit(function() { var theString = $('#string').val(); var varTitle = $('<textarea />').html(theString).text(); $('#output').text(varTitle); return false; }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="#" method="post"> <fieldset> <label for="string">Enter a html-encoded string to decode</label> <input type="text" name="string" id="string" /> </fieldset> <fieldset> <input type="submit" value="decode" /> </fieldset> </form> <div id="output"></div>

J.S.小提琴。

因为@Robert K和@mattcasey都有很好的代码,我想在这里贡献一个CoffeeScript版本,以防将来有人会使用它:

    String::unescape = (strict = false) ->
      ###
      # Take escaped text, and return the unescaped version
      #
      # @param string str | String to be used
      # @param bool strict | Stict mode will remove all HTML
      #
      # Test it here:
      # https://jsfiddle.net/tigerhawkvok/t9pn1dn5/
      #
      # Code: https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d
      ###
      # Create a dummy element
      element = document.createElement("div")
      decodeHTMLEntities = (str) ->
        if str? and typeof str is "string"
          unless strict is true
            # escape HTML tags
            str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';')
          else
            str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')
            str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '')
          element.innerHTML = str
          if element.innerText
            # Do we support innerText?
            str = element.innerText
            element.innerText = ""
          else
            # Firefox
            str = element.textContent
            element.textContent = ""
        unescape(str)
      # Remove encoded or double-encoded tags
      fixHtmlEncodings = (string) ->
        string = string.replace(/\&amp;#/mg, '&#') # The rest, for double-encodings
        string = string.replace(/\&quot;/mg, '"')
        string = string.replace(/\&quote;/mg, '"')
        string = string.replace(/\&#95;/mg, '_')
        string = string.replace(/\&#39;/mg, "'")
        string = string.replace(/\&#34;/mg, '"')
        string = string.replace(/\&#62;/mg, '>')
        string = string.replace(/\&#60;/mg, '<')
        string
      # Run it
      tmp = fixHtmlEncodings(this)
      decodeHTMLEntities(tmp)

请参阅https://jsfiddle.net/tigerhawkvok/t9pn1dn5/7/或https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d(包括编译过的JS,可能比这个答案更新了)

我知道我有点晚了,但我认为我可以提供以下片段作为我如何使用jQuery解码HTML实体的示例:

var varTitleE = "Chris&apos; corner";
var varTitleD = $("<div/>").html(varTitleE).text();

console.log(varTitleE + " vs. " + varTitleD);​​​​​​​​​​​

不要忘记启动检查器/firebug以查看控制台结果——或者简单地将console.log(…)替换为/alert(…)

也就是说,以下是我的控制台通过谷歌Chrome检查器读取的内容:

Chris&apos; corner vs. Chris' corner