2

In my jquery script I need to dynamically translate some content, so part of such function is

$('#password').attr('placeholder', 'Contraseña');

where I tried to change placeholder attribute to text Contraseña.

Unfortunatelly, jquery shows text Contraseña

What does a trick to force jquery to show correct decoded text?

Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • 1
    See the following SO Question about encoding HTML in Javascript : http://stackoverflow.com/questions/1219860/html-encoding-in-javascript-jquery – Nunners Oct 07 '13 at 15:21
  • 1
    Use unicode: \u00F1 for lowercase n with tilde and \u00D1 for uppercase. – Speedy Oct 07 '13 at 15:24
  • 2
    You should use UTF-8 consistently in your project – then there would be _no need_ to “encode” such characters in the first place … – CBroe Oct 07 '13 at 15:29

1 Answers1

6

You have to escape special characters using JavaScript syntax, not HTML syntax.

$('#password').attr('placeholder', 'Contrase\u00f1a');

Personally I'd use .prop() instead of .attr() too, though both should work here.

The general procedure is to

  1. Find the numeric equivalent for the HTML escape (for example, ñ can also be written ñ);
  2. Convert the decimal numeric representation to hex (so, 241 -> F1);
  3. Write a JavaScript \uNNNN escape with the 4-digit version of the hex value.

edit — "CBroe" makes the good point that if you maintain your source as a UTF-8 file, then you can just directly code that character and it should work:

$('#password').attr('placeholder', 'Contraseña');

For that to work requires that your server correctly sends out headers with the appropriate character encoding value, but you really should do that anyway. The hex escape will work even if you are correctly storing and serving UTF-8 of course.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Is there some handy function for such conversion when I have string encoded in HTML syntax..? – Ωmega Oct 07 '13 at 15:23
  • @Ωmega well not that I know of. There are several sources on the web with handy tables of HTML entities, and most show numeric versions. The irritating part is that mostly people use decimal notation for HTML entities, while JavaScript unicode escapes require hex. – Pointy Oct 07 '13 at 15:25
  • Also things get weird when you're messing with characters beyond the 16-bit UTF-16 range. – Pointy Oct 07 '13 at 15:27