LoginSignup
4
5

More than 3 years have passed since last update.

JavaScriptでクエリパラメータを取得

Last updated at Posted at 2020-11-30

方法

new URL(decodeURIComponent(document.location.href)).searchParams.get(<keyName>)

で取得できます。

解説

http://example.com/?param1=hoge&param2=fuga

例えばこのようなクエリパラメーターつきのURLがあるとします。
それぞれparam1param2の値である"hoge""fuga"を取得したいと思います。

URLを取得

document.location.href
// "http://example.com/?param1=hoge&param2=fuga"

パーセントエンコーディングに対応させる場合

decodeURIComponent(document.location.href)

このようにしてデコードできます。

パラメータを取得

new URL(decodeURIComponent(document.location.href))
// URL {...}

先ほどのURLからURLオブジェクトを作ります。

new URL(decodeURIComponent(document.location.href)).searchParams
// URLSearchParams {...}
new URL(decodeURIComponent(document.location.href)).searchParam.get("param1")
// "hoge"
new URL(decodeURIComponent(document.location.href)).searchParam.get("param2")
// "fuga"

そしてURLSearchParamsオブジェクトに対して、getメソッドでキーを指定することでパラメータを得ることができます。

4
5
1

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
4
5