点我去Gitee
点我去Gitee

获取url后面的内容

原文连接:https://blog.csdn.net/debruyne/article/details/70313371

一、获取url内容

//设置或获取对象指定的文件名或路径。
alert(window.location.pathname);

//设置或获取整个 URL 为字符串。
alert(window.location.href);

//设置或获取与 URL 关联的端口号码。
alert(window.location.port);


//设置或获取 URL 的协议部分。
alert(window.location.protocol);

//设置或获取 href 属性中在井号“#”后面的分段。
alert(window.location.hash);

//设置或获取 location 或 URL 的 hostname 和 port 号码。
alert(window.location.host);

//设置或获取 href 属性中跟在问号后面的部分。
alert(window.location.search);

二、获取url=后面的内容(只有一个参数)

let url = window.location.search; 
let neirong = url.substring(url.indexOf('=')+1, url.length); 

三、获取url后面的参数(有多个参数) 把参数转成对象

// console.log(location.search)//http://127.0.0.1:5500/into.html?userName=111&password=222333&submit=%E6%8F%90%E4%BA%A4
// 把问号去掉
let removeMark=location.search.substr(1)//userName=111&password=222333&submit=%E6%8F%90%E4%BA%A4
// console.log(removeMark)
// 分割&  得到每组数据
let group=removeMark.split('&')//["userName=111", "password=222333", "submit=%E6%8F%90%E4%BA%A4"]
// console.log(group)

let list=[]//最终得到的  里卖弄是对象的数组数据
// 用map把每组数据变成对象
let data=group.map((groupItem,groupIndex)=>{
    // 获取等号的下标
    let eq=groupItem.indexOf('=')
    // console.log(eq)
    // 获取键值对的键和值
    let pre=groupItem.slice(0,eq)
    let back=groupItem.slice(eq+1)
    // console.log(pre,back)
    // 拼接成对象
    let obj={}
    obj[pre]=back
    list.push(obj)
})
console.log(list)//) [{userName: "111"},{password: "222333"},{submit: "%E6%8F%90%E4%BA%A4"}]

//得到url的值
for(var i=0;i<list.length;i++){
    list[i].password&&console.log(list[i].password)
}
posted @ 2021-10-16 10:32  biuo  阅读(451)  评论(0)    收藏  举报