How to get URL parameter using jQuery or plain JavaScript?

前端 未结 30 3207
天涯浪人
天涯浪人 2020-11-21 06:29

I have seen lots of jQuery examples where parameter size and name are unknown.

My URL is only going to ever have 1 string:

http://example.com?sent=ye         


        
30条回答
  •  抹茶落季
    2020-11-21 06:59

    I always stick this as one line. Now params has the vars:

    params={};location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v})
    

    multi-lined:

    var params={};
    window.location.search
      .replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
        params[key] = value;
      }
    );
    

    as a function

    function getSearchParams(k){
     var p={};
     location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
     return k?p[k]:p;
    }
    

    which you could use as:

    getSearchParams()  //returns {key1:val1, key2:val2}
    

    or

    getSearchParams("key1")  //returns val1
    

提交回复
热议问题