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.">
search
HomeWeb Front-endFront-end Q&AHow to implement gbk encoding in javascript

How to implement gbk encoding in javascript

Jan 18, 2022 am 11:14 AM
gbkjavascript

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
How to Use useState() Hook in Functional React ComponentsHow to Use useState() Hook in Functional React ComponentsApr 30, 2025 am 12:25 AM

useState allows state to be added in function components because it removes obstacles between class components and function components, making the latter equally powerful. The steps to using useState include: 1) importing the useState hook, 2) initializing the state, 3) using the state and updating the function.

React's View-Focused Nature: Managing Complex Application StateReact's View-Focused Nature: Managing Complex Application StateApr 30, 2025 am 12:25 AM

React's view focus manages complex application state by introducing additional tools and patterns. 1) React itself does not handle state management, and focuses on mapping states to views. 2) Complex applications need to use Redux, MobX, or ContextAPI to decouple states, making management more structured and predictable.

Integrating React with Other Libraries and FrameworksIntegrating React with Other Libraries and FrameworksApr 30, 2025 am 12:24 AM

IntegratingReactwithotherlibrariesandframeworkscanenhanceapplicationcapabilitiesbyleveragingdifferenttools'strengths.BenefitsincludestreamlinedstatemanagementwithReduxandrobustbackendintegrationwithDjango,butchallengesinvolveincreasedcomplexity,perfo

Accessibility Considerations with React: Building Inclusive UIsAccessibility Considerations with React: Building Inclusive UIsApr 30, 2025 am 12:21 AM

TomakeReactapplicationsmoreaccessible,followthesesteps:1)UsesemanticHTMLelementsinJSXforbetternavigationandSEO.2)Implementfocusmanagementforkeyboardusers,especiallyinmodals.3)UtilizeReacthookslikeuseEffecttomanagedynamiccontentchangesandARIAliveregio

SEO Challenges with React: Addressing Client-Side Rendering IssuesSEO Challenges with React: Addressing Client-Side Rendering IssuesApr 30, 2025 am 12:19 AM

SEO for React applications can be solved by the following methods: 1. Implement server-side rendering (SSR), such as using Next.js; 2. Use dynamic rendering, such as pre-rendering pages through Prerender.io or Puppeteer; 3. Optimize application performance and use Lighthouse for performance auditing.

The Benefits of React's Strong Community and EcosystemThe Benefits of React's Strong Community and EcosystemApr 29, 2025 am 12:46 AM

React'sstrongcommunityandecosystemoffernumerousbenefits:1)ImmediateaccesstosolutionsthroughplatformslikeStackOverflowandGitHub;2)Awealthoflibrariesandtools,suchasUIcomponentlibrarieslikeChakraUI,thatenhancedevelopmentefficiency;3)Diversestatemanageme

React Native for Mobile Development: Building Cross-Platform AppsReact Native for Mobile Development: Building Cross-Platform AppsApr 29, 2025 am 12:43 AM

ReactNativeischosenformobiledevelopmentbecauseitallowsdeveloperstowritecodeonceanddeployitonmultipleplatforms,reducingdevelopmenttimeandcosts.Itoffersnear-nativeperformance,athrivingcommunity,andleveragesexistingwebdevelopmentskills.KeytomasteringRea

Updating State Correctly with useState() in ReactUpdating State Correctly with useState() in ReactApr 29, 2025 am 12:42 AM

Correct update of useState() state in React requires understanding the details of state management. 1) Use functional updates to handle asynchronous updates. 2) Create a new state object or array to avoid directly modifying the state. 3) Use a single state object to manage complex forms. 4) Use anti-shake technology to optimize performance. These methods can help developers avoid common problems and write more robust React applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools