思路:
- 通过location的search就可以获取到url中问号后面的值。
- 字符串过滤到问号
- 通过split方法分割参数集合
- 循环赋值
- 匹配对应的参数值
- 返回值
function getUrlParams(name) { // 不传name返回所有值,否则返回对应值
var url = window.location.search;
if (url.indexOf('?') == 1) { return false; }
url = url.substr(1);
url = url.split('&');
var name = name || '';
var nameres;
// 获取全部参数及其值
for(var i=0;i<url.length;i++) {
var info = url[i].split('=');
var obj = {};
obj[info[0]] = decodeURI(info[1]);
url[i] = obj;
}
// 如果传入一个参数名称,就匹配其值
if (name) {
for(var i=0;i<url.length;i++) {
for (const key in url[i]) {
if (key == name) {
nameres = url[i][key];
}
}
}
} else {
nameres = url;
}
// 返回结果
return nameres;
}
实例
const url = 'http://www.abc.com/test.php?id=1&from=index';
var res = getUrlParams();
var res1 = getUrlParams('id');
console.log(res); // [{id: "1"}, {from: "index"}]
console.log(res1); // 1
其他
window.location:
| 属性 | 描述 |
|---|---|
| hash | 设置或获取 href 属性中在井号“#”后面的分段。 |
| host | 设置或获取 location 或 URL 的 hostname 和 port 号码。 |
| hostname | 设置或获取 location 或 URL 的主机名称部分。 |
| href | 设置或获取整个 URL 为字符串。 |
| pathname | 设置或获取对象指定的文件名或路径。 |
| port | 设置或获取与 URL 关联的端口号码。 |
| protocol | 设置或获取 URL 的协议部分。 |
| search | 设置或获取 href 属性中跟在问号后面的部分。 |
eg:
http://localhost:8086/topic/index?topicId=361
console.log(window.location.host):输出:http:localhost:8086console.log(window.location.href);:输出:http://localhost:8086/topic/index?topicId=361console.log(window.location.pathname);:输出:/topic/indexconsole.log(window.location.port):输出:8086console.log(window.location.protocol);:输出: http:console.log(window.location.search);:输出:?topicId=361
参考: