[removed].search query as JSON

2019-02-01 12:58发布

Is there a better way to convert a URL's location.search as an object? Maybe just more efficient or trimmed down? I'm using jQuery, but pure JS can work too.

var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {};
$.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; });

9条回答
家丑人穷心不美
2楼-- · 2019-02-01 13:16

Just wanted to share this solution using a bit of ESNext and a reducer.

It does pretty much the same suggested by @Carlo but it's a bit cleaner if you're comfortable with ES6 and reducers.

const urlSearchData = searchString => {
    if (!searchString) return false;

    return searchString
        .substring(1)
        .split('&')
        .reduce((result, next) => {
            let pair = next.split('=');
            result[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);

            return result;
        }, {});
};

const searchData = urlSearchData(window.location.search);
查看更多
Anthone
3楼-- · 2019-02-01 13:16

Building on @rafaelbiten's ES6 work, I added support for params that have no value and query param arrays of the duplicate entry style.

JSFiddle: https://jsfiddle.net/w922xefs/

const queryStringToJSObject = searchString => {
  if (!searchString) return null;

  return searchString
    .replace(/^\?/, '') // Only trim off a single leading interrobang.
    .split('&')
    .reduce((result, next) => {
      if (next === "") {
        return result;
      }
      let pair = next.split('=');
      let key = decodeURIComponent(pair[0]);
      let value = typeof pair[1] !== "undefined" && decodeURIComponent(pair[1]) || undefined;
      if (result.hasOwnProperty(key)) { // Check to see if this property has been met before.
        if (Array.isArray(result[key])) { // Is it already an array?
          result[key].push(value);
        }
        else { // Make it an array.
          result[key] = [result[key], value];
        }
      }
      else { // First time seen, just add it.
        result[key] = value;
      }

      return result;
    }, {}
  );
};

// Simple read of query string
const searchData = queryStringToJSObject(window.location.search);
查看更多
迷人小祖宗
4楼-- · 2019-02-01 13:21

Note --No doubt above solution works, but it wont cover all the operators

Guess you would want something like this-

var search = location.search;
var trimmedSearch = search.substring(1);

var searchObj = trimmedSearch?JSON.parse(
   '{"' + trimmedSearch.replace(/&/g, '","').replace(/=/g,'":"') + '"}', 
    function(key, value) { 
       return key===""?value:decodeURIComponent(value) 
    }
)
:
{}

console.log(searchObj);

ex -

Override search @1st line with

search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";

Output you get is

Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}
查看更多
趁早两清
5楼-- · 2019-02-01 13:24

Here's a pure JS function. Parses the search part of the current URL and returns an object. (It's a bit verbose for readability, mind.)

function searchToObject() {
  var pairs = window.location.search.substring(1).split("&"),
    obj = {},
    pair,
    i;

  for ( i in pairs ) {
    if ( pairs[i] === "" ) continue;

    pair = pairs[i].split("=");
    obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
  }

  return obj;
}

On a related note, you're not trying to store the single parameters in "a JSON" but in "an object". ;)

查看更多
爷、活的狠高调
6楼-- · 2019-02-01 13:28

In case someone is looking just to access the search query parameters, use this function:

function getQueryStringValue (key)
{
    return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"))
}

Easy to use just call getQueryStringValue(term)

查看更多
老娘就宠你
7楼-- · 2019-02-01 13:30

If you are using modern browser this produce the same result as accepted answer:

function searchToObject(search) {
  return search.substring(1).split("&").reduce(function(result, value) {
    var parts = value.split('=');
    if (parts[0]) result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
    return result;
  }, {})
}
查看更多
登录 后发表回答