Get query string parameter from URL in JavaScript

2019-09-13 23:47发布

I'm looking for a way to extract the query parameters and their corresponding values from a url.

For example. If I have the URL: http://example.com/home?key=value

How can I find the value of key

1条回答
Summer. ? 凉城
2楼-- · 2019-09-14 00:17

Use this function. It's inspired from riot.route.query()

getQuery( [url] ) returns an object containing every key, value pair in the query of window.location.href or the optional url parameter.

var iFrameUrls = [
    'http://www.kk.com/home/add.do?select=inputText',
    '?select=verifyText&this=foo%20bar',
    'http://www.kk.com/home/add.do?select=confirmText'
    ];

function getQuery(url) {
    var query = {},
        href = url || window.location.href;
        
    href.replace(/[?&](.+?)=([^&#]*)/g, function (_, key, value) {
        query[key] = decodeURI(value).replace(/\+/g, ' ');
    });
    
    return query;
}

for (var i = 0, l = iFrameUrls.length; i < l; i++)
  console.log( getQuery( iFrameUrls[i] ) );

查看更多
登录 后发表回答