LoginSignup
98
77

More than 3 years have passed since last update.

URLクラスとURLSearchParamsクラスの使い方メモ

Last updated at Posted at 2018-05-22

urlをいじくり回すのはもうこれだけあればいいじゃんと思ったのでメモ。

元になるurl: http://example.com/hoge/?a=1#foo


URLクラス

const url = new URL(window.location);
url.href; // http://example.com/hoge/?a=1#foo

URLSearchParamsクラス

const params = new URLSearchParams(window.location.search);
params.toString(); // a=1

pathnameを置換する

const url = new URL(window.location);
url.pathname = '/bar/';
url.href; //  // http://example.com/bar/?a=1#foo

searchを置換する

const url = new URL(window.location);
url.search = 'b=あ';
url.href; // http://example.com/hoge/?b=%E3%81%82#foo

hashを置換する

const url = new URL(window.location);
url.hash = 'bar';
url.href; // http://example.com/hoge/?a=1#bar

searchとhashを削除する

const url = new URL(window.location);
url.search = '';
url.hash = '';
url.href; // http://example.com/hoge/

searchに追加する

const url = new URL(window.location);
url.searchParams.append('a', 2);
url.href; // http://example.com/hoge/?a=1&a=2#foo

URLSearchParamsをオブジェクトからインスタンス化する

const params = new URLSearchParams({ 'b': 2 });
params.toString(); // b=2

URLSearchParamsを配列からインスタンス化する

const params = new URLSearchParams([['b', 1], ['b', 2]]);
params.toString(); // b=1&b=2

searchをURLSearchParamsで置換する

const url = new URL(window.location);
const params = new URLSearchParams([['b', 1], ['b', 2]]);
url.search = params;
url.href; // http://example.com/hoge/?b=1&b=2#foo
98
77
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
98
77