LoginSignup
0
0

More than 3 years have passed since last update.

(JSメモ)IE未対応のUrlSearchParamsの機能をpolyfillを使わずに補完するための関数

Last updated at Posted at 2020-11-23

同じような機能の関数は既に幾つかQiitaに転がっているようですが、ハッシュ(URL末尾の# + 任意の文字列)などを考慮していない(最後のパラメータの値にハッシュが混入してしまう)、あるいはパラメータ部分のみ入力して使うことを想定しているものばかりだったので、「ハッシュ付きURL」「相対パスのURL」「パラメータのみ」であっても正確にパラメータをパースできる関数を書きました。

関数

var _URL = function(url){
    return(function(o,u,a,b,c,d){
        return(d=a?(function(_){
            return((a[0]=='?')?(b=_):(c=_),u.slice(0,a.index))
        })(u.slice(a.index+1)):u,
        d==''&&(d=null),
        b&&(((c=b.split(/#(.*?)$/))&&(c=c.length-1?((b=c[0]),c[1]):null)),b.split('&').filter(function(v){
            return v
        }).forEach(function(v){
            (function(_){
                o[_[1]]=_[2]
            })(v.match(/(.+?)=(.*)/))
        })),{base:d,hash:c,param:o})
    })({},url,url.match(/\?|#.*?$/))
};

縮小版

var _URL = function(url){return(function(o,u,a,b,c,d){return(d=a?(function(_){return((a[0]=='?')?(b=_):(c=_),u.slice(0,a.index))})(u.slice(a.index+1)):u,d==''&&(d=null),b&&(((c=b.split(/#(.*?)$/))&&(c=c.length-1?((b=c[0]),c[1]):null)),b.split('&').filter(function(v){return v}).forEach(function(v){(function(_){o[_[1]]=_[2]})(v.match(/(.+?)=(.*)/))})),{base:d,hash:c,param:o})})({},url,url.match(/\?|#.*?$/))};

使い方

console.log(
    _URL('https://www.youtube.com/watch?v=BoZ0Zwab6Oc&t=56s#contents')
);
{
    base: "https://www.youtube.com/watch",
    hash: "contents",
    param: {
        v: "BoZ0Zwab6Oc",
        t: "56s"
    }
}

console.log(
    _URL('/watch?v=BoZ0Zwab6Oc&t=56s')
);
{
    base: "/watch",
    hash: null,
    param: {
        v: "BoZ0Zwab6Oc",
        t: "56s"
    }
}

console.log(
    _URL('?v=BoZ0Zwab6Oc&t=56s#')
);
{
    base: null,
    hash: "",
    param: {
        v: "BoZ0Zwab6Oc",
        t: "56s"
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0