59
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Organization

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

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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
59
Help us understand the problem. What are the problem?