encodeURIComponent を使ってURLエンコードをしたいけど、エスケープされない文字もエンコードしたいときの方法です。
-
encodeURIComponent
アルファベット、10進数字、- _ . ! ~ * ' ( ) はエスケープしないので下記の方法で対応。
メソッド
例: . (ドット)と、 - (ハイフン) も URL エンコードしたい場合、/[.-]/g
を指定するとよいです。
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[.-]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
使い方
str = "hoge-abcd.foo-efg";
res = fixedEncodeURIComponent(str);
console.log(res);
// "hoge%2dabcd%2efoo%2defg"
参考文献 : MDN encodeURIComponent()
encodeURIComponent は次を除く全ての文字をエスケープします : アルファベット、10進数字、- _ . ! ~ * ' ( )