markzzz
markzzz

Reputation: 47995

html entities in a javascript alert?

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?

Upvotes: 9

Views: 10765

Answers (3)

DimeCadmium
DimeCadmium

Reputation: 340

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 = "•";
  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="•"); does not work in any of the browsers I tested!)

Upvotes: 2

Imperative
Imperative

Reputation: 3183

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;

Upvotes: 14

gregjer
gregjer

Reputation: 2843

var encoded = "This is à string";
var decoded = $("<div/>").html(encoded).text();
alert(decoded);

Upvotes: 12

Related Questions