Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

javascript - 在字符串中编码斯堪的纳维亚字母的有效方法(Efficient way to encode scandinavian letters in a string)

My JavaScript get string value from server:

(我的JavaScript从服务器获取字符串值:)

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.

(该name将显示在网页上,因为name包含斯堪的纳维亚字母(例如,名称可能是T?yoe?v? ),因此我需要对其进行编码以使其在浏览器中正确显示。)

In JavaScript, what is the most efficient way to encode all those Scandinavian letters?

(在JavaScript中,对所有这些斯堪的纳维亚字母进行编码的最有效方法是什么?)

( I prefer to do it with Javascript. )

(( 我更喜欢使用JavaScript。 ))

(eg I would like to create a JS function which takes T?yoe?v? as parameter and returns T?yoe?v?)

((例如,我想创建一个将T?yoe?v?作为参数并返回T?yoe?v?的JS函数))

var encoder=function(string){
  for(var s=0; s<string.length; s++){
        //Check each letter in the string, if it is Scandinavian, encode it?? 
  }

}
  ask by Leem translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd advise you not to encode in the JS.

(我建议您不要在JS中编码。)

Just make sure your (html) page encoding matches what your server is returning.

(只要确保您的(html)页面编码与服务器返回的内容匹配即可。)

Preferably, that would be a UTF-8 encoding (to be able to support other languages down the road).

(最好是UTF-8编码(以便将来能够支持其他语言)。)

But if it's just Scandinavian languages you're interested in, ISO-8859-1 (Latin 1) is enough.

(但是,如果您只是对斯堪的纳维亚语言感兴趣,那么ISO-8859-1(拉丁文1)就足够了。)

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.

(因此,您必须在Javascript中知道服务器正在发送的编码。)

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).

(因此,总而言之,从服务器获取编码A到在客户端转换为编码B将非常棘手,并且几乎浪费时间(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可以省去您的头痛。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...