簡體   English   中英

Javascript:encodeURI()/ encodeURIComponent()charset

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

有沒有辦法在Javascript的encodeURI()或encodeURIComponent()中指定charset? 例如:

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

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

我的解決方案是使用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的函數。

根據您在修改此問題之前的早期編輯,您似乎正在嘗試根據您提交的不同搜索字詞訪問各種百度百科。 我的答案與你的新JS問題無關,但是對你的舊問題的簡單解決方案(並且不需要JS解決方案)是在百度Baike URL中指定字符編碼: &enc= 以下所有解決方法都正確:

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與所希望的編碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM