在字符串中编码斯堪的纳维亚字母的有效方法
我的 JavaScript 从服务器获取字符串值:
var name = VALUE_FROM_SERVER;
此 name
将显示在网页上,因为 name
包含斯堪的纳维亚字母(例如,名称可能是 TÖyoeävä em>)我需要以某种方式对其进行编码才能在浏览器上正确显示它。
在 JavaScript 中,对所有这些斯堪的纳维亚字母进行编码的最有效方法是什么?
(我更喜欢用 Javascript 来完成。)
(例如,我想创建一个 JS 函数,它将 TÖyoeävä 作为参数并返回 TÖyoeävä)
var encoder=function(string){
for(var s=0; s<string.length; s++){
//Check each letter in the string, if it is Scandinavian, encode it??
}
}
My JavaScript get string value from server:
var name = VALUE_FROM_SERVER;
This name
will be shown on a web page, since name
contains Scandinavian letter (for example, name could be TÖyoeävä) I need to encode it somehow to display it correctly on the browser.
In JavaScript, what is the most efficient way to encode all those Scandinavian letters?
(I prefer to do it with Javascript.)
(e.g. I would like to create a JS function which takes TÖyoeävä as parameter and returns TÖyoeävä)
var encoder=function(string){
for(var s=0; s<string.length; s++){
//Check each letter in the string, if it is Scandinavian, encode it??
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议你不要在JS中编码。只需确保您的 (html) 页面编码与服务器返回的内容相匹配。
最好是 UTF-8 编码(以便能够支持其他语言)。但如果您只是对斯堪的纳维亚语言感兴趣,ISO-8859-1(拉丁语 1)就足够了。
无法从随机字节字符串中判断它是一种编码还是另一种编码(一般来说无论如何)。所以你必须在 Javascript 中知道服务器发送的编码是什么。
您还必须在某个时刻设置页面的编码,并且该点必须在浏览器开始解释其内容之前。
总而言之,从服务器获取编码 A 并在客户端转换为编码 B 将会很棘手,而且几乎是浪费时间(IMO)。除了允许服务器更改编码之外,您没有获得我所看到的任何灵活性,这似乎不是一个好主意。
一路UTF-8会让你省去很多麻烦。
I'd advise you not to encode in the JS. Just make sure your (html) page encoding matches what your server is returning.
Preferably, that would be a UTF-8 encoding (to be able to support other languages down the road). But if it's just Scandinavian languages you're interested in, ISO-8859-1 (Latin 1) is enough.
There's no way to tell from a random byte string if it's one encoding or another (generally speaking anyway). So you have to know in your Javascript what encoding the server is sending.
You also have to set your page's encoding at some point, and that point has to be before the browser starts interpreting its content.
So all in all, getting encoding A from the server en converting to encoding B on the client side is going to be tricky, and pretty much a waste of time (IMO). You're not gaining any flexibility that I can see, except allowing your server to change encodings, which doesn't seem like such a good idea.
UTF-8 all the way will save you headaches.
从服务器发送响应时只需使用 UTF-8 字符集。例如
Just use the UTF-8 charset when sending the response from the server. For example