1.只能包含?号后面的参数
var str2='https://www.baidu.com/s?wd=JS&rsv_spt=1&a=1&b=2';
str2=str2.split('?')[1].split('&');
var obj={};
str2.forEach((item)=>{
var inner=item.split('=');
obj[inner[0]]=inner[1];
});
var str2='https://www.baidu.com/s?wd=JS&rsv_spt=1&a=1&b=2';
var res3=str2.split('?');
var ary=res3[1].split('&');
var obj={};
//item是数组中的每一项 index是该项索引
//forEach是数组的方法,只能在数组中用
ary.forEach((item,index)=>{
var inner=item.split('=');
var shuxingming=inner[0];
var shuxingzhi=inner[1];
obj[shuxingming]=shuxingzhi;
})
2.可以获取?urlencoded 值和哈希值
url?的值 叫做 urlencoded #号后边的值叫做 哈希值
function queryURLParsms(url) {
let askIndex = url.indexOf('?'),
poIndex = url.lastIndexOf('#'),
poText = '',
askText = '';
//如果poIndex不存在
poIndex === -1?poIndex = url.length:null;
poText = url.substring(poIndex + 1);
if (askIndex > -1) {
askText = url.substring(askIndex + 1, poIndex);
}
var obj = {};
if (askText) {
askText.split("&").forEach(item => {
var arr = item.split("=")
obj[arr[0]] = arr[1];
});
}
if (poText.length > 0) {
obj["_HASH"] = poText;
}
return obj;
};
let url = "http://www.zhufengpeixun.cn/?lx=1&from=wx#video";
let ur2 = "http://www.zhufengpeixun.cn/";
3.内置类 利用a标签的herf属性
String.prototype.queryURLParams = function queryURLParams(parms) {
let link = document.createElement('a');
link.href = this;
let askText = link.search.substring(1),
poText = link.hash.substring(1),
obj = {};
poText ? obj['_HASH'] = poText : null;
if (askText) {
let arr = askText.split(/(?:&|=)/g);
for (let i = 0; i < arr.length; i += 2) {
obj[arr[i]] = arr[i + 1];
}
}
return parms?obj[parms]:'';
}
let url = "http://www.zhufengpeixun.cn/?lx=1&from=wx#video";
console.log(url.queryURLParams("from")); //=>"wx"
console.log(url.queryURLParams("_HASH")); //=>"video"
4.利用正则
String.prototype.queryURLParams = function queryURLParams(parms) {
let link = document.createElement('a');
link.href = this;
let askText = link.search.substring(1),
poText = link.hash.substring(1),
obj = {};
poText ? obj['_HASH'] = poText : null;
if (askText) {
let arr = askText.split(/(?:&|=)/g);
for (let i = 0; i < arr.length; i += 2) {
obj[arr[i]] = arr[i + 1];
}
}
return parms?obj[parms]:'';
}
let url = "http://www.zhufengpeixun.cn/?lx=1&from=wx#video";
console.log(url.queryURLParams("from")); //=>"wx"
console.log(url.queryURLParams("_HASH")); //=>"video"
String.prototype.queryURLParams = function queryURLParams() {
// this->url
let obj = {};
this.replace(/#([^?&#=]+)/g, (_, $1) => obj['HASH'] = $1);
this.replace(/([^?&#=]+)=([^?&#=]+)/g, (_, $1, $2) => obj[$1] = $2);
return obj;
};
let url = 'http://www.zhufengpeixun.cn/index.html?name=xxx&age=12#teacher';
console.log(url.queryURLParams());
// {name:'xxx',age:'12',HASH:'teacher'}