html entities in a javascript alert?

2019-01-19 22:26发布

问题:

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?

回答1:

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


回答2:

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;


回答3:

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!)