0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

基本的な作成方法

// 1. 空で作成
const params = new URLSearchParams();

// 2. 現在のURLから取得
const params1 = new URLSearchParams(location.search);

// 3. 文字列から作成
const params2 = new URLSearchParams('page=2&sort=name');

// 4. オブジェクトから作成
const params3 = new URLSearchParams({ page: '2', sort: 'name' });

主要メソッド

メソッド 説明
set(key, value) 上書きして設定 params.set('page', '3')
append(key, value) 追加(同じkey複数可) params.append('tag', 'js')
get(key) 1つ目の値取得 params.get('page')
getAll(key) 全値取得(配列) params.getAll('tag')
delete(key) 削除 params.delete('page')
has(key) 存在確認 params.has('page')
toString() 文字列化 params.toString()

実用例

// ソート条件を追加
const params = new URLSearchParams(location.search);
params.set('sort', 'name:asc');
params.set('page', '1');
const url = `/api/users?${params.toString()}`;
// → /api/users?sort=name:asc&page=1

// 全パラメータ取得
console.log(Object.fromEntries(params.entries()));
// → { sort: "name:asc", page: "1" }

出力例

const params = new URLSearchParams();
params.set('page', '2');
params.append('tag', 'js');
params.append('tag', 'react');
console.log(params.toString());
// → page=2&tag=js&tag=react
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?