5

有没有办法在 Javascript 的 encodeURI() 或 encodeURIComponent() 中指定字符集?例如:

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

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

4

3 回答 3

3

我的解决方案是使用 npm 包urlencodebrowserify

在 urlencode.js 中编写:

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

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

在 bundle.js 中,声明了一个被调用的函数encode

于 2016-10-01T01:29:16.557 回答
1

根据您修改之前对该问题的早期编辑,您似乎正在尝试根据您提交的不同搜索词访问各种百度百科。我的回答与您的新 JS 问题无关,但您的旧问题的简单解决方案(并且不需要 JS 解决方案)是在百度百科 URL 中指定字符编码:&enc=. 以下所有正确解决:

于 2013-08-06T07:43:38.183 回答
0
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('');

替换encoding为所需的编码

于 2019-02-20T06:40:14.143 回答