How to get URL parameter using jQuery or plain JavaScript?

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

    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'];
    

提交回复
热议问题