HTML Character Entities in Javascript

Sunday, April 25, 2010 - 6:34 pm
By Colin

Sometimes you need to write html character entities in javascript, but html character entities can’t be used, because they don’t get interpreted by javascript. In javascript, you need to use the equivalent unicode character codes instead.

HTML character entity, wrong:
formElement.value = "Dirección";
You get: Dirección

Unicode character code, correct:
formElement.value = "Direcci\u00F3n";
You get: Dirección

Unicode character charts are located here: http://www.unicode.org/charts/. The chart you will most likely need is the Latin-1 chart.  Character codes must be preceded by \u. That is, character code 00F3 is written in JavaScript as \u00F3.

Hope this helps.

Leave a Reply