How to get URL parameter using jQuery or plain JavaScript?

前端 未结 30 3293
天涯浪人
天涯浪人 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: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];
        }
    })();
    

提交回复
热议问题