如何从location.search获取特定参数? [英] How can I get a specific parameter from location.search?

查看:1027
本文介绍了如何从location.search获取特定参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个URL,例如

If I had a URL such as

http://localhost/search.php?year=2008

我如何编写JavaScript函数来获取变量 year 并查看它是否包含什么?

How would I write a JavaScript function to grab the variable year and see if it contains anything?

我知道可以用 location.search 完成但我无法弄清楚它是如何抓住的参数。

I know it can be done with location.search but I can’t figure out how it grabs parameters.

推荐答案

我最喜欢获取URL参数的方法是这种方法:

My favorite way for getting URL params is this approach:

var parseQueryString = function() {

    var str = window.location.search;
    var objURL = {};

    str.replace(
        new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
        function( $0, $1, $2, $3 ){
            objURL[ $1 ] = $3;
        }
    );
    return objURL;
};

//Example how to use it: 
var params = parseQueryString();
alert(params["foo"]); 

这篇关于如何从location.search获取特定参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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