我是使用javascript的新手。例如,我有以下网址:index.jsp?page=home&lang=eng
如何从上面的网址中提取参数home
和eng
?
答案 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