从JavaScript中的URL获取查询字符串参数 [英] Get query string parameter from URL in JavaScript

查看:75
本文介绍了从JavaScript中的URL获取查询字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种从URL中提取查询参数及其对应值的方法。

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

例如。如果我有URL: http://example.com/home?key=value

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

如何找到 key

推荐答案

的值。它的灵感来自 riot.route.query()

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

getQuery([url])返回一个包含每个 的对象 window.location.href 的查询中的键 对或可选的 url 参数。

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

这篇关于从JavaScript中的URL获取查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆