Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print roman languages (e.g. Spanish) /special characters in Javascript?

I've done some research and turns out that to encode special characters we use encodeURI(component) and decodeURI.

However when I try do something like:

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

A "question mark" is printed.

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

Effectively when I do

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

it prints ñ.

But if I try with:

decodeURI(encodeURI('ñ'))

I still get a "question mark".

How does character enconding work in JS? And where can I find a really comprehensive special characters' in encodeURI format (ready out-of-the-box to be decoded via decodeURI)?

EDIT:

  • in my (the application is an AngularJS application) I have meta charset=utf-8 (written in the right HTML syntax as proposed in the answer, it actually comes from AngularJS' starter project)
  • I'm using WebStorm IDE: I checked out the settings and the enconding used is UTF-8
  • I'm serving the page locally in Apache (XAMPP)

EDIT 2: as advised in the answers, I created a .htaccess file in /htdocs whose content is:

AddDefaultCharset UTF-8

as well as renaming both index.html and the view's file by adding .utf8 before .html file extension.

then I restarted Apache (from XAMPP console).

But the issue is not gone. Any clue?

EDIT 3: I finally even tried to open the file in Sublime Text 3 and save as UTF-8 file, nothing changes

like image 387
dragonmnl Avatar asked Oct 29 '25 10:10

dragonmnl


1 Answers

You don't have to do any special encoding in your JS strings (apart for the special case of strings which may be seen as script element closing).

If your JS file encoding matches the HTTP header (most commonly UTF-8), it's decoded if you just do

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

To help the browser, and assuming you're correctly serving the files with the relevant HTTP header (the way it's set up highly depends on your server), you should have this meta tag in you HTML header:

<meta charset='utf-8'>

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

<script charset="UTF-8" src="yourFile.js"></script>
like image 132
Denys Séguret Avatar answered Oct 31 '25 01:10

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!