6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

window.location.search(クエリ)を object にする

Posted at

まえがき

URL の ? 以降の文字列(いわゆる window.location.search )(いわゆるクエリ)を JavaScript の object にする。
大体いつも必要になるので、すぐに引っ張ってきて utils ディレクトリにでも置いておきたいやつ。

🔶 JavaScript

function getSearchObj(searchStr) {
  if (!searchStr) return {};
  return searchStr
    .substr(1)
    .split("&")
    .reduce((acc, cur) => {
      acc[cur.split("=")[0]] = cur.split("=")[1];
      return acc;
    }, {});
}

🔷 TypeScript

function getSearchObj(searchStr: string): { [key: string]: string } {
  if (!searchStr) return {};
  return searchStr
    .substr(1)
    .split("&")
    .reduce(
      (acc, cur) => {
        acc[cur.split("=")[0]] = cur.split("=")[1];
        return acc;
      },
      {} as { [key: string]: string }
    );
}
6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?