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?

More than 5 years have passed since last update.

Typescript(Javascript)でURLクエリパラメーターを更新する

Posted at

URLクエリパラメーターを更新するクラス

※ Typescriptで書いてます。Javascriptの場合は型指定あたりを削除すれば動くと思います。

class MySearchParams {
    static update(key: string, value: string): boolean {
        const params = MySearchParams.toObject();
        params[key] = value;
        const url = "?" + Object.keys(params).map(
            (key: string) => key + "=" + params[key]).join("&");
        history.replaceState('', '', url);
        history.pushState('', '', url);

        return true;
    }

    static get(key: string): string {
        const params: any = MySearchParams.toObject();
        return params[key];
    }

    static toObject(): Object {
        let vars = {}, max: number, hash: any, array: any = "";
        let url = window.location.search;

        if (url.length === 0) {
            return vars;
        }
        hash = url.slice(1).split('&');
        max = hash.length;
        for (let i = 0; i < max; i++) {
            array = hash[i].split('=');
            vars[array[0]] = array[1];
        }

        return vars;
    }
}

使い方は以下のとおり

指定パラメーターの更新

MySearchParams.update(key, value)

全てのパラメーターを連想配列で取得

MySearchParams.toObject()

指定パラメーターの取得

MySearchParams.get(key)

ブラウザのバージョンなどによっては、動作しないかもです。問題点などありましたら、コメントなどで指摘していただけると助かります<m(_ _)m>

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?