How do I print romance languages ​​(like Spanish) / special characters in Javascript?

I did some research and found out that we use encodeURI (component) and decodeURI to encode special characters .

However, when I try to do something like:

var my_special_char = 'ñ';
my_div.innerHTML = decodeURI(encodeURI(my_special_char))

      

A "question mark" is printed.

I found this (incomplete) table about special characters: http://www.javascripter.net/faq/accentedcharacters.htm

Effective when I do

decodeURI("%C3%B1"); // ñ

      

it prints - .

But if I try:

decodeURI(encodeURI('ñ'))

      

I am still getting a "question mark".

How does a character work in JS? And where can I find really all-round special characters in encodeURI format (ready-to-use code that needs to be decoded via decodeURI )?

EDIT

  • in my app (app is AngularJS app) I have meta charset = utf-8 (written in correct HTML syntax as suggested in the answer, it actually comes from the AngularJS starter project)
  • I am using WebStorm IDE : I checked the settings and the application being used is UTF-8
  • I am serving a page locally in Apache (XAMPP)

EDIT 2 : As the answers said, I created a .htaccess file at / htdocs whose content is:

AddDefaultCharset UTF-8

      

and also rename index.html and the view file by adding .utf8 before the .html extension .

then I restarted Apache (from XAMPP console).

But the problem persisted. Any hint?

EDIT 3 . Finally, I even tried to open the file in Sublime Text 3 and save as UTF-8 file, nothing changed

+3


source to share


3 answers


You don't need to do any special encoding in your JS strings (separately for the special case of strings that might be thought of as closing a script element).

If your JS file encoding matches the HTTP header (most often UTF-8) it is decoded if you just do

var my_special_char = 'ñ';
my_div.innerHTML = my_special_char;

      

To help the browser, and assuming you are serving files correctly with the appropriate HTTP header (how it is configured is highly dependent on your server), you should have this meta tag in your HTML header:



<meta charset='utf-8'>

      

If your script is in a separate file, you must also declare the encoding in the script element:

<script charset="UTF-8" src="yourFile.js"></script>

      

+2


source


You have to add <meta charset="utf-8" />

to your tag head

. This way the browser knows which encoding to use and there will be no more question marks :)



+2


source


in the classic notepad, which he solved by pressing

File> Save As> dropdown menu Encoding> UTF-8

in notepad ++ click

Encoding> Encoding in UTF-8

or by adding charset attribute to metatag charset='utf-8'

<meta charset='utf-8'>

      

0


source







All Articles