9

I have a string coming from a XML (which I can't edit) and I'd like to print it trough an alert in javascript.

Example of my string:

This is à string

And I need to print in an alert:

This is à string

is there a js html decode?

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
markzzz
  • 47,390
  • 120
  • 299
  • 507

3 Answers3

14

you could put the string in a dom element and read it out again, even without jquery: https://stackoverflow.com/a/3700369/1986499

Edit by recent demand to include some code from another SO answer:

var div = document.createElement('div');
div.innerHTML = encoded;
var decoded = div.firstChild.nodeValue;
Community
  • 1
  • 1
Imperative
  • 3,138
  • 2
  • 25
  • 40
11
var encoded = "This is à string";
var decoded = $("<div/>").html(encoded).text();
alert(decoded);
gregjer
  • 2,823
  • 2
  • 19
  • 18
  • 5
    What this answer fails to mention is that, despite the question not being tagged with it, **you need the jQuery library to use this answer**. Without jQuery you'll be greeted with a lovely DOMException error. – James Donnelly May 20 '15 at 08:45
1

I'm just a tiny bit late, but just in case anyone else finds this via Google (like I did), I thought I'd improve upon Imperative's answer.

function showbullet() {
  var tempelement = document.createElement('div');
  tempelement.innerHTML = "&bull;";
  alert("Here, have a bullet!\n" + tempelement.innerHTML);
}
showbullet();

I've tested this and confirmed it works in Chrome/43.0.2357.130 m; Firefox/32.0.1; Internet Explorer/9.0.8112.16421. There's no need to go mucking about with nodeValue's and what not; the entity will be replaced with it's associated character as soon as the assignment is complete. (Note, however, that doing alert(tempelement.innerHTML="&bull;"); does not work in any of the browsers I tested!)

Community
  • 1
  • 1
DimeCadmium
  • 314
  • 2
  • 9