How can I get a specific parameter from location.s

2019-01-04 02:09发布

This question already has an answer here:

If I had a URL such as

http://localhost/search.php?year=2008

How would I write a JavaScript function to grab the variable year and see if it contains anything?

I know it can be done with location.search but I can’t figure out how it grabs parameters.

14条回答
淡お忘
2楼-- · 2019-01-04 02:11

My favorite way for getting URL params is this approach:

var parseQueryString = function() {

    var str = window.location.search;
    var objURL = {};

    str.replace(
        new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
        function( $0, $1, $2, $3 ){
            objURL[ $1 ] = $3;
        }
    );
    return objURL;
};

//Example how to use it: 
var params = parseQueryString();
alert(params["foo"]); 
查看更多
Rolldiameter
3楼-- · 2019-01-04 02:12

This is what I like to do:

window.location.search
    .substr(1)
    .split('&')
    .reduce(
        function(accumulator, currentValue) {
            var pair = currentValue
                .split('=')
                .map(function(value) {
                    return decodeURIComponent(value);
                });

            accumulator[pair[0]] = pair[1];

            return accumulator;
        },
        {}
    );

Of course you can make it more compact using modern syntax or writing everything into one line...

I leave that up to you.

查看更多
欢心
4楼-- · 2019-01-04 02:16

It took me a while to find the answer to this question. Most people seem to be suggesting regex solutions. I strongly prefer to use code that is tried and tested as opposed to regex that I or someone else thought up on the fly.

I use the parseUri library available here: http://stevenlevithan.com/demo/parseuri/js/

It allows you to do exactly what you are asking for:

var uri = 'http://localhost/search.php?year=2008';
var year = uri.queryKey['year'];
// year = '2008'
查看更多
Luminary・发光体
5楼-- · 2019-01-04 02:16

Grab the params from location.search with one line:

const params = new Map(this.props.location.search.slice(1).split('&').map(param => param.split('=')))

Then, simply:

if(params.get("year")){
  //year exists. do something...
} else {
  //year doesn't exist. do something else...
}
查看更多
Anthone
6楼-- · 2019-01-04 02:17

I used a variant of Alex's - but needed to to convert the param appearing multiple times to an array. There seem to be many options. I didn't want rely on another library for something this simple. I suppose one of the other options posted here may be better - I adapted Alex's because of the straight forwardness.

parseQueryString = function() {
    var str = window.location.search;
    var objURL = {};

    // local isArray - defer to underscore, as we are already using the lib
    var isArray = _.isArray

    str.replace(
        new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
        function( $0, $1, $2, $3 ){

            if(objURL[ $1 ] && !isArray(objURL[ $1 ])){
                // if there parameter occurs more than once, convert to an array on 2nd
                var first = objURL[ $1 ]
                objURL[ $1 ] = [first, $3]
            } else if(objURL[ $1 ] && isArray(objURL[ $1 ])){
                // if there parameter occurs more than once, add to array after 2nd
                objURL[ $1 ].push($3)
            }
            else
            {
                // this is the first instance
                objURL[ $1 ] = $3;
            }

        }
    );
    return objURL;
};
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-04 02:18

ES6 answer:

const parseQueryString = (path = window.location.search) =>
  path.slice(1).split('&').reduce((car, cur) => {
   const [key, value] = cur.split('=')
   return { ...car, [key]: value } 
  }, {})

for example:

parseQueryString('?foo=bar&foobar=baz')
// => {foo: "bar", foobar: "baz"}
查看更多
登录 后发表回答