0

I'm trying to remove ' from my string. How to do that? I'm using ajax with JSON. My code looks like this:

<html>
    <body>
    <p id="testHTML"></p>
    </body>
    <script type="text/javascript">
            
        $(document).ready(function() {
            $.ajaxSetup({ cache: false });
            setInterval(function() {
                $.getJSON("IOCounter.html", function(data) {
                    $('#testHTML').text(data.testHTML);
                });
            }, 2000); //Refreshrate in ms
        });
    </script>
    </html>

Inside testHTML, I get the string "HelloWorld" from IOCounter.html but when I display it inside index.html I get:

&#x27;HelloWorld&#x27;

Now I just want to remove &#x27; to get only HelloWorld. What do I have to do?

Kunal Kukreja
  • 662
  • 4
  • 13
Sfedo
  • 21
  • 8
  • The string returned is `html` encoded. To decode, use this: https://stackoverflow.com/a/34064434 – Kunal Kukreja Aug 19 '20 at 08:22
  • I've seen this post before, but I cant get where to place htmlDecode in my own code and how to use it with p tag... Sorry I'm very new into coding with html and javascript – Sfedo Aug 19 '20 at 08:28
  • Just decode it before adding the element. Seeing your code, it seems, you would need to decode `data.testHTML` and then set it to `#testHTML`. e.g. ```$('#testHTML').text(htmlDecode(data.testHTML));``` . Just make sure `htmlDecode` function is defined and available. – Kunal Kukreja Aug 19 '20 at 08:40
  • ok thank you so far, my HTML decodes it now, but the refresh function doesnt work – Sfedo Aug 19 '20 at 08:59
  • It should work. Since you are receiving the `data` once, then the request must also be working fine. If not, then chain your getJSON with a `.fail()` and add a callback to check the `error`. – Kunal Kukreja Aug 19 '20 at 10:26
  • Added the solution to an answer so that it helps others. – Kunal Kukreja Aug 22 '20 at 14:24

1 Answers1

0

The string returned is HTML encoded. To get a plain text string, it needs to be decoded.

DOMParser (supported in most browsers) can be used to decode the string as follows:

function htmlDecode(str) {
    const doc = new DOMParser().parseFromString(str, "text/html");
    return doc.documentElement.textContent;
}

Using this, you can decode the string and then set it to #textHTML.

$.getJSON("IOCounter.html", function(data) {
    $('#testHTML').text(htmlDecode(data.testHTML));
});
Kunal Kukreja
  • 662
  • 4
  • 13