What's the right way to decode a string that has special HTML entities in it?

Say I get a JSON response like this:

{
  "message": "We're unable to complete your request at this time."
}
I'm not sure why the apostrophe shows up as ', but I'd really like to decode that into a normal quote. I tried using jQuery like this:

function decodeHtml(html) {
  return $('<div>').html(html).text();
}

It works, but honestly feels kind of hacky.

Is there a more reliable or proper way to do a javascript html decode operation?

That jQuery method might feel hacky, but it’s actually a common and safe approach. DOM parsing handles the decoding natively.

If you’re not using jQuery, you can do the same in vanilla JS:

function decodeHtml(html) {
  const txt = document.createElement("textarea");
  txt.innerHTML = html;
  return txt.value;
}

Super handy if you’re doing any javascript html decode tasks without extra libraries!

@smrity.maharishsarin I have used the same method you mentioned, and while it looks a bit meh but it’s reliable.

Another clean vanilla JS way is using DOMParser, especially if you’re already dealing with markup:

function decodeHtml(html) {
  return new DOMParser().parseFromString(html, "text/html").documentElement.textContent;
}

Great for quick javascript html decode needs and works in most modern browsers.

Honestly, your method is solid @Ambikayache & @tim-khorev .

I use it all the time when parsing strings from APIs. There isn’t a built-in decodeEntities() in JavaScript, so yeah, leveraging the browser’s HTML parser is actually the clever move.

Whether through jQuery or native DOM, either way, it’s the go-to for a JavaScript HTML decode situation.

Hope this helped :slight_smile: