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
- 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
3 Answers
Reset to default 3My 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
版权声明:本文标题:url - Javascript: encodeURI()encodeURIComponent() charset - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745301442a2652395.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论