简体   繁体   中英

Defining the character encoding of a JavaScript source file

I would like to print a status message to my German users, which contains umlauts (ä/ü/ö). I also would like them be in the source file rather than having to download and parse some extra file just for the messages.

However, I can't seem to find a way to define the encoding of a JS source file. Is there something like HTML's http-equiv ? Or should I define the encoding in the HTTP header?

When I simply encode the file in UTF-8 an serve it, IE displays garbage.

Sending the encoding in the headers is always a good idea.

If that's not possible, the <script> tag has the charset property. W3C Reference

<script src="translations.js" type="text/javascript" charset="utf-8"/>

似乎在HTML5中不推荐使用脚本标记的charset属性(仅对a和link标记不推荐使用它)。

While the charset parameter would seem helpful, it's important to note that it's actually deprecated in HTML5.

http://www.w3.org/International/questions/qa-html-encoding-declarations#charset

This might sound a bit dumb, but make sure you save your javascript file with the correct encoding in the editor you are using. I had a problem with the encoding of my javascript file, and the solution was as simple as this!

对于法语javascript js,我们使用了另一个字符集:

<script src="./js/MyScript.js" type="text/javascript" charset="iso-8859-1"></script>

The simplest solution to your problem would be to use unicode escape for special character in strings. This way, your code is not affected by the page that's hosting it.

A tool that might help you: http://www.webstein.net/tools/javascript-unicode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM