How to get URL parameter using jQuery or plain JavaScript?

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

    So simple you can use any url and get value

    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
    

    Usage Example

    // query string: ?first=value1&second=&value2
    var foo = getParameterByName('first'); // "value1"
    var bar = getParameterByName('second'); // "value2" 
    

    Note: If a parameter is present several times (?first=value1&second=value2), you will get the first value (value1) and second value as (value2).

提交回复
热议问题