简体   繁体   English

Javascript:encodeURI()/ encodeURIComponent()charset

[英]Javascript: encodeURI() / encodeURIComponent() charset

Is there any way to specify charset in Javascript's encodeURI() or encodeURIComponent()? 有没有办法在Javascript的encodeURI()或encodeURIComponent()中指定charset? Eg: 例如:

encodeURIComponent("例子", "UTF-8") outputs %E4%BE%8B%E5%AD%90 encodeURIComponent("例子", "UTF-8")输出%E4%BE%8B%E5%AD%90

encodeURIComponent("例子", "GBK") outputs %C0%FD%D7%D3 encodeURIComponent("例子", "GBK")输出%C0%FD%D7%D3

My solution is to used a npm package urlencode and browserify . 我的解决方案是使用npm包urlencodebrowserify

Write in urlencode.js: 写在urlencode.js:

var urlencode = require("urlencode");
module.exports = function (s) { return urlencode(s, "gbk"); }

browserify urlencode.js --s encode > bundle.js

And in bundle.js, a function called encode is declared. 在bundle.js中,声明了一个名为encode的函数。

Based on the earlier edit of this question before you revised it, it seems like you're trying to access various Baidu Baike based on different search terms you submit. 根据您在修改此问题之前的早期编辑,您似乎正在尝试根据您提交的不同搜索字词访问各种百度百科。 My answer is not relevant to your new JS question, but the simple solution to your old problem (and would obviate the need for a JS solution) is to specify the character encoding in the Baidu Baike URL: &enc= . 我的答案与你的新JS问题无关,但是对你的旧问题的简单解决方案(并且不需要JS解决方案)是在百度Baike URL中指定字符编码: &enc= All the following resolve correctly: 以下所有解决方法都正确:

const _encodeURIComponent = (x) =>
    x   
        .split('')
        .map((y) => {
            if (!RegExp(/^[\x00-\x7F]*$/).test(y)) {
                return iconv
                    .encode(y, encoding)
                    .reduce((a, b) => a + '%' + b.toString(16), '') 
                    .toUpperCase();
            } else {
                return y;
            }   
        })  
        .join('');

Replace encoding with desired encoding 替换encoding与所希望的编码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM