1

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/

Community
  • 1
  • 1
user911
  • 1,509
  • 6
  • 26
  • 52
  • 3
    Don't do that. You should use `text`, not `html`. – SLaks Feb 23 '17 at 19:50
  • Thanks @SLaks! I tried that but it doesn't work for me. I have a .css('someClass').html(formattedData) .appendTo(container); text() function doesn't fit here. I am getting error. – user911 Feb 23 '17 at 20:07

2 Answers2

4

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>
m87
  • 4,445
  • 3
  • 16
  • 31
  • This doesn't work for me . I have a .css('someClass').html(formattedData) .appendTo(container); text() function doesn't fit here. I am getting error. – user911 Feb 23 '17 at 20:06
  • can you please elaborate? – m87 Feb 23 '17 at 20:13
  • string could be a html {A+_2OF3_MSF} . Will text() work? – user911 Feb 23 '17 at 20:18
  • YES! why not? check edit. also if there's any additional quotes in that string then you need to escape it by putting a backslash `\\` before it. – m87 Feb 23 '17 at 20:23
  • @siam `.text()` will remove HTML tags and HTML entities I believe. – dokgu Feb 23 '17 at 20:44
  • @uom-pgregorio: No; it will just set the text to whatever you pass. – SLaks Feb 23 '17 at 21:01
  • @SLaks somehow this [Fiddle](https://jsfiddle.net/7vf252sa/) seems to remove the `span` tags though. – dokgu Feb 23 '17 at 21:09
  • @Siam - I can't use text. I want html at the end which can be rendered as html and not as plain text. I would expect the output of your fiddle to be just {A+_"2OF3_MSF"} not {A+_"2OF3_MSF"} – user911 Feb 23 '17 at 21:42
  • @user911 oh..then you need to set an id for the span. see update ^ – m87 Feb 24 '17 at 06:10
3

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;'));
    });
});
Choo Hwan
  • 416
  • 3
  • 12