How to get the value from the GET parameters?

I have a URL with some GET parameters as follows:

www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 

I need to get the whole value of c . I tried to read the URL, but I got only m2 . How do I do this using JavaScript?


JavaScript itself has nothing built in for handling query string parameters.

In a (modern) browser you can use the URL object;

var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);

Most implementations I've seen miss out URL-decoding the names and the values.

Here's a general utility function that also does proper URL-decoding:

function getQueryParams(qs) {
    qs = qs.split('+').join(' ');

    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
}

//var query = getQueryParams(document.location.search);
//alert(query.foo);

资源

function gup( name, url ) {
    if (!url) url = location.href;
    name = name.replace(/[[]/,"[").replace(/[]]/,"]");
    var regexS = "[?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    return results == null ? null : results[1];
}
gup('q', 'hxxp://example.com/?q=abc')
链接地址: http://www.djcxy.com/p/25314.html

上一篇: 在一个客户端上使用多个SSH私钥的最佳方法

下一篇: 如何从GET参数中获取值?