[WebAPIs] URL 與 URLSearchParams API
keywords: URL, URLSearchParams, query string, params
URL 物件
// new URL(<url>, <base>);
// 建立 URL 物件
new URL('https://www.google.com/foo'); // https://www.google.com/foo
new URL('bar', 'https://www.google.com/foo'); // https://www.google.com/bar
// 建立 Hash Tag
var url = new URL('https://example.com/path?foo=1&bar=2');
url.hash = 'hashTag';
// 取得 url 資訊
url.href; // "https://example.com/path?foo=1&bar=2"
url.hostname; // "example.com"
url.pathname; // "/path"
url.search; // "?foo=1&bar=2"
url.protocol; // "https:"
// 可以用的方法
url.toString(); // "https://example.com/path?foo=1&bar=2"
URL SearchParams
建立 URL SearchParams 物件
// 方法一:直接代入 URL
var url = new URL('https://example.com/path?foo=1&bar=2');
var qs = new URLSearchParams(url.search);
// 方法二:代入陣列
var qs = new URLSearchParams([
['foo', 1],
['bar', 2],
]);
// 方法三:代入物件
var qs = new URLSearchParams({ foo: 1, bar: 2 });
// 都會得到一樣的結果
qs.toString(); // "foo=1&bar=2"
設定 SearchParams 可使用的方法
var url = new URL('https://example.com/path');
var qs = new URLSearchParams();
// 添加 append(<key>, <value>),如果有重複的 key 仍然會繼續向後添加
qs.append('q', 'reactJS');
url.search = qs;
url.href; // "https://example.com/path?q=reactJS"
// 設定 set(<key>, <value>),如果有重複的 key,則會設定其中一個,其他的刪除
qs.set('q', 'Vue');
url.search = qs; // "https://example.com/path?q=Vue"
url.href;
// 刪除 delete(<key>)
qs.delete('q');
url.search = qs;
url.href; // "https://example.com/path"