How to get URL parameter using jQuery or plain JavaScript?

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

    jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:

    $.urlParam = function(name){
        var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
        if (results==null) {
           return null;
        }
        return decodeURI(results[1]) || 0;
    }
    

    example.com?param1=name¶m2=&id=6

    $.urlParam('param1'); // name
    $.urlParam('id');        // 6
    $.urlParam('param2');   // null
    

    example params with spaces

    http://www.jquery4u.com?city=Gold Coast
    console.log($.urlParam('city'));  
    //output: Gold%20Coast
    
    
    
    console.log(decodeURIComponent($.urlParam('city'))); 
    //output: Gold Coast
    

提交回复
热议问题