How to get URL parameter using jQuery or plain JavaScript?

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

提交回复
热议问题