定义 JavaScript 源文件的字符编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2325079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:47:45  来源:igfitidea点击:

Defining the character encoding of a JavaScript source file

javascriptunicodeencoding

提问by Leonard Ehrenfried

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?

但是,我似乎找不到定义 JS 源文件编码的方法。有没有类似 HTML 的东西http-equiv?还是应该在 HTTP 标头中定义编码?

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

当我简单地用 UTF-8 编码文件并提供它时,IE 显示垃圾。

回答by Pekka

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

在标头中发送编码总是一个好主意。

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

如果这是不可能的,则<script>标签具有该charset属性。W3C 参考

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

回答by Simon Hi

It seems that the charset attribute for the script tag is not deprecated in HTML5 (it is deprecated only for a and link tags).

似乎 HTML5 中不推荐使用 script 标签的 charset 属性(仅不推荐使用 a 和 link 标签)。

回答by Micah Henning

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

虽然 charset 参数看起来很有用,但重要的是要注意它在 HTML5 中实际上已被弃用。

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

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

回答by CptCook

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 文件。我的 javascript 文件的编码有问题,解决方案就这么简单!

回答by Nolm? Informatique

For french javascript js, we've used another charset :

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

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

回答by ra00l

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.

解决您的问题的最简单方法是对字符串中的特殊字符使用 unicode 转义。这样,您的代码就不会受到托管它的页面的影响。

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

一个可以帮助你的工具:http: //www.webstein.net/tools/javascript-unicode