How to get URL parameter using jQuery or plain JavaScript?

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

    Or you can use this neat little function, because why overcomplicated solutions?

    function getQueryParam(param, defaultValue = undefined) {
        location.search.substr(1)
            .split("&")
            .some(function(item) { // returns first occurence and stops
                return item.split("=")[0] == param && (defaultValue = item.split("=")[1], true)
            })
        return defaultValue
    }
    

    which looks even better when simplified and onelined:

    tl;dr one-line solution

    var queryDict = {};
    location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
    
    result:
    queryDict['sent'] // undefined or 'value'
    

    But what if you have got encoded characters or multivalued keys?

    You better see this answer: How can I get query string values in JavaScript?

    Sneak peak

    "?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
    > queryDict
    a: ["1", "5", "t e x t"]
    b: ["2"]
    c: ["3"]
    d: [undefined]
    e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
    
    > queryDict["a"][1] // "5"
    > queryDict.a[1] // "5"
    

提交回复
热议问题