How to get URL parameter using jQuery or plain JavaScript?

前端 未结 30 3190
天涯浪人
天涯浪人 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 07:08

    There is another example with using URI.js library.

    Example answers the questions exactly as asked.

    var url = 'http://example.com?sent=yes';
    var urlParams = new URI(url).search(true);
    // 1. Does sent exist?
    var sendExists = urlParams.sent !== undefined;
    // 2. Is it equal to "yes"?
    var sendIsEqualtToYes = urlParams.sent == 'yes';
    
    // output results in readable form
    // not required for production
    if (sendExists) {
      console.log('Url has "sent" param, its value is "' + urlParams.sent + '"');
      if (urlParams.sent == 'yes') {
        console.log('"Sent" param is equal to "yes"');
      } else {
        console.log('"Sent" param is not equal to "yes"');
      }
    } else {
      console.log('Url hasn\'t "sent" param');
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>

    0 讨论(0)
  • 2020-11-21 07:08

    With vanilla JavaScript, you could easily take the params (location.search), get the substring (without the ?) and turn it into an array, by splitting it by '&'.

    As you iterate through urlParams, you could then split the string again with '=' and add it to the 'params' object as object[elmement[0]] = element[1]. Super simple and easy to access.

    http://www.website.com/?error=userError&type=handwritten

                var urlParams = location.search.substring(1).split('&'),
                    params = {};
    
                urlParams.forEach(function(el){
                    var tmpArr = el.split('=');
                    params[tmpArr[0]] = tmpArr[1];
                });
    
    
                var error = params['error'];
                var type = params['type'];
    
    0 讨论(0)
  • 2020-11-21 07:09

    A slight improvement to Sameer's answer, cache params into closure to avoid parsing and looping through all parameters each time calling

    var getURLParam = (function() {
        var paramStr = decodeURIComponent(window.location.search).substring(1);
        var paramSegs = paramStr.split('&');
        var params = [];
        for(var i = 0; i < paramSegs.length; i++) {
            var paramSeg = paramSegs[i].split('=');
            params[paramSeg[0]] = paramSeg[1];
        }
        console.log(params);
        return function(key) {
            return params[key];
        }
    })();
    
    0 讨论(0)
  • 2020-11-21 07:11

    May be its too late. But this method is very easy and simple

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="jquery.url.js"></script>
    
    <!-- URL:  www.example.com/correct/?message=done&year=1990 -->
    
    <script type="text/javascript">
    $(function(){
        $.url.attr('protocol')  // --> Protocol: "http"
        $.url.attr('path')      // --> host: "www.example.com"
        $.url.attr('query')         // --> path: "/correct/"
        $.url.attr('message')       // --> query: "done"
        $.url.attr('year')      // --> query: "1990"
    });
    

    UPDATE
    Requires the url plugin : plugins.jquery.com/url
    Thanks -Ripounet

    0 讨论(0)
  • 2020-11-21 07:16

    Admittedly I'm adding my answer to an over-answered question, but this has the advantages of:

    -- Not depending on any outside libraries, including jQuery

    -- Not polluting global function namespace, by extending 'String'

    -- Not creating any global data and doing unnecessary processing after match found

    -- Handling encoding issues, and accepting (assuming) non-encoded parameter name

    -- Avoiding explicit for loops

    String.prototype.urlParamValue = function() {
        var desiredVal = null;
        var paramName = this.valueOf();
        window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
            var nameVal = currentValue.split('=');
            if ( decodeURIComponent(nameVal[0]) === paramName ) {
                desiredVal = decodeURIComponent(nameVal[1]);
                return true;
            }
            return false;
        });
        return desiredVal;
    };
    

    Then you'd use it as:

    var paramVal = "paramName".urlParamValue() // null if no match
    
    0 讨论(0)
  • 2020-11-21 07:17

    Another solution that uses jQuery and JSON, so you can access the parameter values through an object.

    var loc = window.location.href;
    var param = {};
    if(loc.indexOf('?') > -1)
    {
        var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");
    
        var stringJson = "{";
        for(var i=0;i<params.length;i++)
        {
            var propVal = params[i].split("=");
            var paramName = propVal[0];
            var value = propVal[1];
            stringJson += "\""+paramName+"\": \""+value+"\"";
            if(i != params.length-1) stringJson += ",";
        }
        stringJson += "}";
        // parse string with jQuery parseJSON
        param = $.parseJSON(stringJson);
    }
    

    Assuming your URL is http://example.com/?search=hello+world&language=en&page=3

    After that it's only a matter of using the parameters like this:

    param.language
    

    to return

    en
    

    The most useful usage of this is to run it at page load and make use of a global variable to use the parameters anywhere you might need them.

    If your parameter contains numeric values then just parse the value.

    parseInt(param.page)
    

    If there are no parameters param will just be an empty object.

    0 讨论(0)
提交回复
热议问题