本文介绍了使用 Javascript 解码 UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个 XHTML 网页中有 Javascript,它传递 UTF-8 编码的字符串.它需要继续传递 UTF-8 版本,并对其进行解码.如何解码 UTF-8 字符串以进行显示?
I have Javascript in an XHTML web page that is passing UTF-8 encoded strings. It needs to continue to pass the UTF-8 version, as well as decode it. How is it possible to decode a UTF-8 string for display?
<script type="text/javascript">
// <![CDATA[
function updateUser(usernameSent){
var usernameReceived = usernameSent; // Current value: Größe
var usernameDecoded = usernameReceived; // Decode to: Größe
var html2id = '';
html2id += 'Encoded: ' + usernameReceived + '<br />Decoded: ' + usernameDecoded;
document.getElementById('userId').innerHTML = html2id;
}
// ]]>
</script>
推荐答案
回答最初的问题:这里是你如何在 javascript 中解码 utf-8:
To answer the original question: here is how you decode utf-8 in javascript:
http://ecmanaut.blogspot.ca/2006/07/encoding-decoding-utf8-in-javascript.html
具体来说,
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
我们已经在我们的生产代码中使用它 6 年了,它运行完美.
We have been using this in our production code for 6 years, and it has worked flawlessly.
但是请注意,escape() 和 unescape() 已被弃用. 看到这个.
这篇关于使用 Javascript 解码 UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!