简体   繁体   中英

Escaping/Unescaping html in javascript?

There are many answered questions on stackoverflow about escaping/unescaping html from js. But I am finding it hard to understand as it doesn't fit my context nicely. I have a variable "message" which has this string:

message="<a href="www.google.com">Google</a>"

I am displaying this message in a js file using "this.message". Instead of seeing the hyperlinked "Google", I can literally see the whole string:

<a href="www.google.com">Google</a>

If I inspect element, I can see that this string is being translated into:

&lt;a href="www.google.com"&gt;Google;&lt;&gt

How do I get the hyperlinked google? Do I have to escape/unescape? How?

Code to display messages:

$.each(mdn.notifications || [], function() {
            $('<div class="notification">' + this.message + '</div>')[insertLocation.method](insertLocation.selector);
        });

Add html formatting in the django template like this:

{% if messages %}notifications: [
                {% for message in messages %}{% if 'wiki_redirect' not in message.tags or waffle.flag('redirect_messages') %}{message: "<div class='my-message'>{{ message }}</div>", tags: "{{ message.tags }}", level: "{{ message|level_tag }}"}{% if not loop.last %},{% endif %}{% endif %}
                {% endfor %}
            ],
            {% else %}
            notifications: [],
            {% endif %}

Or you can add html formatting in client-side javascript like this:

$.each(mdn.notifications || [], function() {
            // Make it so
            $('<div class="notification ' + this.level + ' ' + this.tags + '" data-level="' + this.level + '"><div class="my-message">' + this.message + '</div></div>')[insertLocation.method](insertLocation.selector);
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM