1.首先需要获取当前页面的URL,这个可以从 window.location.search 获取:
//获取当前页面的完整地址
var currentUrl = window.location.href;
//获取当前页面URL的从问号 (?) 开始的 URL(查询部分)
var params = window.location.search;
Location 对象属性
属性 | 描述 |
---|---|
hash | 设置或返回从井号 (#) 开始的 URL(锚)。 |
host | 设置或返回主机名和当前 URL 的端口号。 |
hostname | 设置或返回当前 URL 的主机名。 |
href | 设置或返回完整的 URL。 |
pathname | 设置或返回当前 URL 的路径部分。 |
port | 设置或返回当前 URL 的端口号。 |
protocol | 设置或返回当前 URL 的协议。 |
search | 设置或返回从问号 (?) 开始的 URL(查询部分)。 |
上表来自 http://www.w3school.com.cn/jsref/dom_obj_location.asp
2.获取具体的参数
以Google "JS获取当前页面url参数" 的URL为例:
以下内容转载自: https://blog.csdn.net/tjcyjd/article/details/44275531
但unescape函数替换为了decodeURLcomponent
有两种方法:
(1)split 分割放进对象:
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=decodeURLcomponent(strs[i].split("=")[1]);
}
}
return theRequest;
}
var req = GetRequest();
var query = req['q'];
alert(query);
(2)正则表达式匹配:
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURLcomponent(r[2]); return null;
}
var query= getQueryString("q");
alert(query);
注:
1.window.location.search中包含中文参数时,使用unescape进行解码会出现乱码错误,应该使用 decodeURLComponent函数;
关于 escape encodeURI encodeURIComponent 的区别,请参考:
https://www.cnblogs.com/qiantuwuliang/archive/2009/07/19/1526687.html
主要区别是:
1..escapte unescapte 已经被废弃;
2.encodeURI/decodeURI 用于编码/解码整个URL, encodeURIComponent/decodeURIComponent 用于编码/解码URL的部分参数;