JavaScript 解析浏览器地址URL

获取完整的URL

假设地址栏为 : https://localhost:8080/test?ID=123#top

	//获取地址栏锚地址
	var url= window.location.href

变量值 :

	'https://localhost:8080/test?ID=123#top'

获取Get请求参数

假设地址栏为 : https://www.xxx.com/test?ID=123&&Name=Mike

//获取地址栏请求参数
function getURLArgs() {
	//解析地址栏中的中文字符
    let search = decodeURI(window.location.search)
    let params = {}
    search = search.substring(1, search.length);
    let group = search.split('&')
    for (let i = 0; i < group.length; i++) {
        let entry = group[i].split('=')
        params[entry[0]] = entry[1]
    }
    return params
}

函数返回值 :

{
	ID: "123"
	Name: "Mike"
}

获取主机名

假设地址栏为 : https://localhost:8080/test

	//获取地址栏锚地址
	var hostname= window.location.hostname

变量值 :

	'localhost'

获取端口号

假设地址栏为 : https://localhost:8080/test

	//获取地址栏锚地址
	var port= window.location.port

变量值 :

	'8080'

获取主机名与端口号

假设地址栏为 : https://localhost:8080/test

	//获取地址栏锚地址
	var host= window.location.host

变量值 :

	'localhost:8080'

获取锚地址( # 号后面的部分,包括#)

假设地址栏为 : https://www.xxx.com/test#top

	//获取地址栏锚地址
	var anchorname = window.location.hash

变量值 :

	'#top'

获取抽象路径

假设地址栏为 : https://www.xxx.com/test/index.html?ID=123#top

	//获取地址栏锚地址
	var protocol= window.location.pathname

变量值 :

	'/test/index.html'

获取请求协议

假设地址栏为 : https://www.xxx.com/test#top

	//获取地址栏锚地址
	var protocol= window.location.protocol

变量值 :

	'https:'

详细参考

W3School

猜你喜欢

转载自blog.csdn.net/qq_44460210/article/details/90201632
今日推荐