Unescaping ampersand characters in javascript

2019-05-06 23:22发布

问题:

I'm having trouble properly displaying values that contain escaped characters (i.e. apostrophes are stored as \' and not ' and brackets are &gt; and &lt; rather than > and <).

Items stored in my database have the characters (' < >) escaped to (\' &lt; &gt;), respectively. When I try to dynamically add them to the page with JavaScript, they print out in the escaped form in Firefox, rather than returning to their normal values like in IE (&lt; is being printed to the HTML rather just <).

<html>
    <head>
        <script type="text/javascript">
         $(document).ready(function() {
            var str = "&gt;";
            $(document.body).html(str);
         });
        </script>
    </head>
    <body>

    </body>
</html>

I know that if I simply do a replace, I can print correctly, but by doing so, I'm allowing the injection of HTML code, which is why I escaped the string in the first place.

ADDED:

Firstly, I apologize about the mistakes in my initial post. After closer examination, in the instances where I am using $().html(), the strings are printing correctly. The times where they aren't printing correctly are when I am using code like below.

var str = "&gt;";
$('#inputField').val(str);

In this instance, the text ">" is shown, rather than ">". Is there something I can do to fix this?

回答1:

You need to decode them like this:

$('#myText').val($("<div/>").html(str).text());

Demo: http://jsfiddle.net/QUbmK/

You can move the decode part to function too and call that instead:

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

$('#myText').val(jDecode(str));


回答2:

First off, you can't run the code you have in your example. document.body is not ready for manipulation in the HEAD tag. You have to run that after the document has loaded. If I put your code in a safe place to run, it works fine as you can see here.

So ... there must be more to your situation than the simple example you show here. You can see your simple example works fine here when the code is put in the right place:

http://jsfiddle.net/jfriend00/RDSNz/



回答3:

That doesn't happen, at least not with jQuery. If you do, literally: $(document.body).html('&lt;div&gt;'), you will get <div> printed to the screen, not a div tag. If you're doing something not listed in your question:

either use .text() instead of .html() or replace all & with &amp;:

$(document.body).text(str);
$(document.body).html(str.replace(/&/g, '&amp;'))