admin管理员组

文章数量:1419240

Is there any way to specify charset in Javascript's encodeURI() or encodeURIComponent()? E.g.:

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

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

Is there any way to specify charset in Javascript's encodeURI() or encodeURIComponent()? E.g.:

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

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

Share Improve this question edited Jun 22, 2013 at 10:10 optimizitor asked Feb 13, 2013 at 13:12 optimizitoroptimizitor 91714 silver badges20 bronze badges 2
  • No, these functions are UTF-8 only. What are you trying to acplish? – Christoph Commented Jun 22, 2013 at 10:24
  • @Christoph, it's for a dictionary lookup script that dynamically generates links to UTF-8 and GBK pages based on user input data. Is there any functions that can do GBK encoding? – optimizitor Commented Jun 25, 2013 at 16:41
Add a ment  | 

3 Answers 3

Reset to default 3

My solution is to used a npm package urlencode and browserify.

Write in 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.

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=. All the following resolve correctly:

  • http://baike.baidu./search/word?word=例子&pic=1&sug=1&enc=utf8
  • http://baike.baidu./search/word?word=%E4%BE%8B%E5%AD%90&pic=1&sug=1&enc=utf8
  • http://baike.baidu./search/word?word=%C0%FD%D7%D3&pic=1&sug=1&enc=GBK
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

本文标签: urlJavascript encodeURI()encodeURIComponent() charsetStack Overflow