Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unescaping ampersand characters in javascript

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?

like image 578
Will Reese Avatar asked Jul 14 '11 17:07

Will Reese


People also ask

What is ampersand in JavaScript?

Ampersand. js is optimized for mixing-and-matching with other stuff. Financial Times used ampersand-state and ampersand-view combined with D3. js to make a world debt visualizer. Both WhatsApp and FlipKart use React as the view layer.

What is escaping characters in JavaScript?

Escape Characters are the symbol used to begin an escape command in order to execute some operation. They are characters that can be interpreted in some alternate way than what we intended to. Javascript uses '\' (backslash) in front as an escape character.

How do you check if a character is a special character in JavaScript?

To check if a string contains special characters, call the test() method on a regular expression that matches any special character. The test method will return true if the string contains at least 1 special character and false otherwise.


1 Answers

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));
like image 131
Mrchief Avatar answered Nov 13 '22 09:11

Mrchief