Ever needed to put accented characters such as é into a JavaScript alert? It’s surprisingly problematic. Consider this simple function:
function accentTest1() {
alert('Ménage à trois.')
}
If you invoke the function, you get an alert as expected, but the HTML entities are not entified, they get them spelled out as typed in the code.
To get around this problem, you have to use octal-encoded characters instead of HTML entities:
alert('M\351nage \340 trois.')
PJB has published a handy table for converting between octal, hex and HTML entities.
Craig wrote:
That was a big pain for me – as was getting special characters into generated CSS – too. Finally got frustrated enough to build a rough little DOM-based tool for getting the right values to use in HTML, JavaScript and CSS:
http://www.saila.com/usage/tips/examples/special_characters.html
Gerard wrote:
To avoid the problem, you could have replaced text in your example by “triolisme” :p
Martijn wrote:
With innerHTML comes automatic conversion of html entities:
var y=document.createElement(‘span’);
y.innerHTML=’Ménage à trois.’;
alert(y.innerHTML);
Isn’t innerHTML just lovely?
. wrote:
Why can’t you just put the in your javascript string? If your document is encoded as ISO-8859–1, you don’ t need any entities whatsoever.
Or even better, switch to UTF-8, and never worry about encoding problems altogether.
andré from Paris-France wrote:
I was saved by your the “octal” remarque don’t forget to add an “antislash” before the octal digits in “M351nage 340 trois”
perhaps it was filtered by the host’s blog editor software ?!?
Mnage trois….
Thank you all !