Unescape HTML entities in Javascript?

前端 未结 30 2939
野趣味
野趣味 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:50

    Matthias Bynens has a library for this: https://github.com/mathiasbynens/he

    Example:

    console.log(
        he.decode("Jörg & Jürgen rocked to & fro ")
    );
    // Logs "Jörg & Jürgen rocked to & fro"
    

    I suggest favouring it over hacks involving setting an element's HTML content and then reading back its text content. Such approaches can work, but are deceptively dangerous and present XSS opportunities if used on untrusted user input.

    If you really can't bear to load in a library, you can use the textarea hack described in this answer to a near-duplicate question, which, unlike various similar approaches that have been suggested, has no security holes that I know of:

    function decodeEntities(encodedString) {
        var textArea = document.createElement('textarea');
        textArea.innerHTML = encodedString;
        return textArea.value;
    }
    
    console.log(decodeEntities('1 & 2')); // '1 & 2'
    

    But take note of the security issues, affecting similar approaches to this one, that I list in the linked answer! This approach is a hack, and future changes to the permissible content of a textarea (or bugs in particular browsers) could lead to code that relies upon it suddenly having an XSS hole one day.

提交回复
热议问题