JavaScript/url
来自康健生活
引言
location
| hash | 从 # 开始的 URL
|
| host | 主机名 + 端口号 |
| hostname | 当前 URL 的主机名 |
| href | 完整的 URL |
| pathname | 当前 URL 的路径部分 |
| port | 当前 URL 的端口 |
| protocol | 当前 URL 的协议 |
| serach | 从 ? 开始的 URL
|
正则
function getQueryString(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
};
return null;
}
split
function GetRequest() {
const url = location.search; //获取url中"?"符后的字串
let theRequest = new Object();
if (url.indexOf("?") != -1) {
let str = url.substr(1);
strs = str.split("&");
for(let i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
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;
}
这些示例代码都有问题,有待改正
No categories