![](/img/trans.png)
[英]Issue with javascript escape, encodeURI and encodeURIComponent
[英]Javascript: encodeURI() / encodeURIComponent() charset
有没有办法在Javascript的encodeURI()或encodeURIComponent()中指定charset? 例如:
encodeURIComponent("例子", "UTF-8")
输出%E4%BE%8B%E5%AD%90
encodeURIComponent("例子", "GBK")
输出%C0%FD%D7%D3
我的解决方案是使用npm包urlencode和browserify 。
写在urlencode.js:
var urlencode = require("urlencode");
module.exports = function (s) { return urlencode(s, "gbk"); }
browserify urlencode.js --s encode > bundle.js
在bundle.js中,声明了一个名为encode
的函数。
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.