![](/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.