14
13

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.

URLとかのクエリストリングをよしなに処理したい

14
Last updated at Posted at 2016-10-14

URLのGETパラメータから何かしたり、検索したい条件としてGETパラメータを整形したりするときに、&だとか?だとか気にしながら文字列を連結するのにツラみを感じているあなたへ。

取得するとき

//location.search = '?hoge=2&bar=fuga';
var query = Query.parse(location.search);
console.log(query);
// {hoge:"2", bar: "fuga"}

生成するとき

var param = {hoge: 10, bar: "fuga"};
var api = '/api/v1/hoge?' + Query.stringify(param);
console.log(api);
// "/api/v1/hoge?hoge=10&bar=fuga";

ソースコード

※ 環境にあわせてよしなに変換して使ってください。
※ 4年前の雑コードなのでリファクタリングもよしなに…。

var _ = require('underscore');

var Query = {
    parse: function (query) {
        var parts=  query.replace(/^\?/, '').split('&');
        var params = {};
        _.each(parts, function (value) {
            var part = value.split('=');

            params[part[0]] = part[1];
        });

        return params;
    },
    stringify : function (params) {
        return _.map(params, function (value, key) {
            return key + '=' + value;
        }).join('&');
    },
    parseFromURL: function(url) {
        var matched = url.match(/\?(.*?)#?$/);
        return !matched || !matched.length ? null : this.parse(matched[1]);
    }
};

module.exports = Query;
14
13
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
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?