user911
user911

Reputation: 1559

jQuery 'HTML function doesn't work with special characters

I am trying to pass the string "{<A+_2OF3_MSF}" to jQuery's HTML function. It doesn't work because of special character <. I tried encoding/escaping an HTML tag using this escapeHtml function, but I am facing another issue after that.

var escapeHtml = function(theString) {
            return theString.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
        };

It appends HTML-encoded string as text, not as HTML. I saw the below Stack Overflow post, but then it suggests to decode it after encoding. If I do that I am back to square one.

Appending HTML-encoded string as HTML, not as text

I have created a fiddle:

https://jsfiddle.net/1aktfzm8/

Upvotes: 1

Views: 2485

Answers (2)

m87
m87

Reputation: 4511

You need to use .text() instead of .html()

$(document).ready(function(){
    $("button").click(function(){
        $("p").html("<span id=\"span\"> {A+_\"2OF3_MSF\"} </span>");
        $('#span').text();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Change content of all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

Upvotes: 4

Choo Hwan
Choo Hwan

Reputation: 416

This code is working normally: https://jsfiddle.net/kilotonna/eg4be1gr/1/

$(document).ready(function(){
    $("button").click(function(){
        $("p").html("{<A+_2OF3_MSF}".replace(/</g, '&lt;'));
    });
});

Upvotes: 3

Related Questions