netanalyzer
netanalyzer

Reputation: 634

How to put unicode chars in javascript

I use BaaS for my Front-End. It allows me to upload a javascript file with my backend logic. I can use it via REST API on client side. Among other services I've implemented a localization service. Strings are predefined like this:

var locals = {
"EN": {
    "1": "Home",
    "2": "Ready"
},
"BG": {
    "1": "Начало",
    "2": "Готово"
}

In this example I offer english and bulgarian string's localization. The problem is that BaaS system doesn't respect Cyrillic (Unicode) characters. When I upload the script with content as above, all cyrillic chars are replaced with "????".

I can use this method to resolve the problem, but escape/unescape functions are deprecated. Is there any better solutions? What is the most effective way to avoid this problem?

Upvotes: 1

Views: 267

Answers (1)

bobince
bobince

Reputation: 536339

To reference non-ASCII characters in a JavaScript file that isn't served Unicode-safe, use JS string literal character escapes: \uNNNN where NNNN is a the hex number of the UTF-16 code units associated with the string (same as the code point number for characters like these in the Basic Multilingual Plane).

"BG": {
    "1": "\u041d\u0430\u0447\u0430\u043b\u043e",
    "2": "\u0413\u043e\u0442\u043e\u0432\u043e"
}

List of code points for Cyrillic characters here. You could also use Firefox's toSource method to work it out for you:

> 'Начало'.toSource()
(new String("\u041D\u0430\u0447\u0430\u043B\u043E"))

When I upload the script with content as above, all cyrillic chars are replaced with "????".

Are you sure that is the “BaaS”'s fault? We can't really tell as you haven't told us what the service is or even what kind of service it is.

If it's a JS file you are fetching via Ajax you would need to save the file as UTF-8-encoded to be able to use non-ASCII characters without encoding them as above. If you are including it with a script element you also need to save the HTML page as UTF-8 and include a UTF-8 meta charset directive.

Upvotes: 6

Related Questions