5

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

2
  • No, these functions are UTF-8 only. What are you trying to accomplish?
    – 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? Commented Jun 25, 2013 at 16:41

3 Answers 3

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.

1

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:

2
  • Thank you, this really works with the Baidu. But I still wonder if there is a general and simple way to do it using JS or maybe plain HTML. Commented Aug 7, 2013 at 11:04
  • Sorry for the much belated update @kleopatra! Hope it's easier to read now. Two years later, links still resolve properly. Commented Sep 23, 2015 at 15:04
1
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.