如何获取URI参数 - 使用JavaScript查询字符串?

时间:2013-03-08 09:03:44

标签: javascript jquery

我是使用javascript的新手。例如,我有以下网址:index.jsp?page=home&lang=eng如何从上面的网址中提取参数homeeng

问题也回答:How can I get query string values in JavaScript?

2 个答案:

答案 0 :(得分:3)

解析网址的参数:

var url = 'index.jsp?page=home&lang=eng';

var parse = function (url) {
    var getQuery = url.substring(url.indexOf('?') + 1);
    var parts = getQuery.split('&');
    var key = null;
    var value = null;
    var result = {};
    for (var i = 0; i < parts.length; i++) {
        var keyValue = parts[i].split('=');
        key = keyValue[0];
        value = keyValue[1];
        result[key] = value;
    }
    return result;
};

parse(url)的输出将是具有以下结构的对象:

{
    page: "home",
    lang: "eng"
}

答案 1 :(得分:1)

提取所需的确切网址参数的简便方法,当找不到您搜索的参数时,将返回“”空字符串:

function getUrlParam(param){
 var value = decodeURIComponent(
  (RegExp(param + '=' + '(.+?)(&|$)').exec(location.search)||["",""])[1]);
 return value;
} 

page_value = getUrlParam("page");    // home
lang_value = getUrlParam("lang");    // eng