url - Javascript: encodeURI()encodeURIComponent() charset - Stack Overflow

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745301443a4621459.html

相关推荐

  • url - Javascript: encodeURI()encodeURIComponent() charset - Stack Overflow

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

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信