dragonmnl
dragonmnl

Reputation: 15548

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:

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

Upvotes: 4

Views: 1242

Answers (3)

Egy Success
Egy Success

Reputation: 112

in classic notepad it solved by clicking

file > Save As > in Encoding dropdown menu > UTF-8

in notepad++ by click

Encoding > Encode in UTF-8

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

<meta charset='utf-8'>

Upvotes: 0

Jack
Jack

Reputation: 1769

You should add <meta charset="utf-8" /> inside your head tag. In this way the browser knows which charset to use and no more question marks will appear :)

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382170

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>

Upvotes: 3

Related Questions