gbk code" mapping table in js and solve it by looking up the table; 2. Use escapeDBC and encodeURIComponent for encoding."/> gbk code" mapping table in js and solve it by looking up the table; 2. Use escapeDBC and encodeURIComponent for encoding.">

Home  >  Article  >  Web Front-end  >  How to implement gbk encoding in javascript

How to implement gbk encoding in javascript

藏色散人
藏色散人Original
2022-01-18 11:14:154292browse

javascript实现gbk编码的方法:1、在js建立一个“字符->gbk码”的映射表,通过查表来解决;2、使用escapeDBC和encodeURIComponent进行编码。

How to implement gbk encoding in javascript

本文操作环境:Windows7系统、javascript1.8.5版、Dell G3电脑。

javascript 怎么实现gbk编码?

Javascript对中文GBK编码

今天帮同事弄一个在迅雷新闻上展示的页面,里面的搜索功能对关键词用的是GBK编码,而他们给我的页面上GB2312的,造成搜索功能的关键词乱码。后面google了一下,找到了解决方案,很有效。

以”超级本“这个关键词为例:

GB2312下编码后为%E8%B6%85%E7%BA%A7%E6%9C
GBK下编码后为%B3%AC%BC%B6%B1%BE

在 js 中要怎样实现使用gbk集进行 uri 编码呢

%HH 其实就只是把一个字节值转换成2位16进制数字,再在前头加上 % 而己

问题是 js 中没有函数可以支持取得字符的 gbk 编码值   str.charCodeAt(index)  取得的是 unicode 编码值。

现在在网上流行的一种解决方案就是,在 js 建立一个 “字符->gbk码” 的映射表,通过查表来解决

因为字符多,这使得 js 雍肿了不少,而且在网上找到的这些映射表建的是不是全面,很难说。

其实在 ie 中,我们可以借助 VBScript 来支持这个工作。

VBScript 中: (Asc(“盟”) + 65536) Mod 65536  就可以取得字符 “盟” 的 GBK 码 50123

但是其它浏览器不支持 VBScript ,可怎么办?

有这么一个办法:

在页面中插入一个图片 img,   设置 img.src = “…中文…”;  这个时候,浏览器会自动把这个 src 的值进行 uri 编码

而它是使用 gbk 还是 utf8 ,是根据文档编码来决定的.

这时候,我们就可以好好利用一下这个特性:

<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<script type="text/javascript">
function encodeURL(s) {
var img = document.createElement("img");
// escapeDBC 对多字节字符编码的函数
function escapeDBC(s) {
if (!s) return ""
if (window.ActiveXObject) {
// 如果是 ie, 使用 vbscript
execScript(‘SetLocale "zh-cn"’, ‘vbscript’);
return s.replace(/[\d\D]/g, function($0) {
window.vbsval = "";
execScript(‘window.vbsval=Hex(Asc("’ + $0 + ‘"))’, "vbscript");
return "%" + window.vbsval.slice(0,2) + "%" + window.vbsval.slice(-2);
});
}
// 其它浏览器利用浏览器对请求地址自动编码的特性
img.src = "nothing.action?separator=" + s;
return img.src.split("?separator=").pop();
}
// 把 多字节字符 与 单字节字符 分开,分别使用 escapeDBC 和 encodeURIComponent 进行编码
return s.replace(/([^\x00-\xff]+)|([\x00-\xff]+)/g, function($0, $1, $2) {
return escapeDBC($1) + encodeURIComponent($2||”);
});
}
alert(encodeURL("中文"));
</script>

推荐学习:《javascript基础教程

The above is the detailed content of How to implement gbk encoding in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn