获取url中携带的参数进行处理,拿到所需值

就拿我写页面来说:let url = 'https://editor.csdn.net/md?not_checkout=1'
观察这个结构,?后面携带的参数

not_checkout=1

现在我们就来拿到这个参数
首先我们拿到这个url:

window.location.href
//https://editor.csdn.net/md?not_checkout=1
//注:在某些APP H5页面上面会自动屏蔽掉?后面的字段,我所使用到的解决办法是用#代替?
window.location.search
//?not_checkout=1

我们已经拿到携带的参数片段,现在对这个片段进行处理
去除?

window.location.search.substring(1)
//not_checkout=1

看现在我们已经拿到了这个参数,这是一个简单的url,但是往往我们实际中,并不会这么简单
比如let url='https://editor.csdn.net/md?not_checkout=1&data=asdawdac155w&type=mqkwmql'这样的url
同样的

window.location.search.substring(1)
//not_checkout=1&data=asdawdac155w&type=mqkwmql

将得到的分割成字符串

window.location.search.substring(1).split("&")
//(2)["not_checkout=1","data=asdawdac155w","type=mqkwmql"]

如果我们需要拿到一个单独的值,仅仅需要通过遍历来切割成单独的一个数组

for (var i=0;i<window.location.search.substring(1).split("&").length;i++) {
var pair = window.location.search.substring(1).split("&")[i].split("=");
	console.log(pair)
	//(2) ["data", "asdawdac155w"]
	//(2) ["type", "mqkwmql"]
	//这里我们来拿type的值
	if(pair[0] === type){
		console.log(pair[1])
		//mqkwmql
	}
}

我们可以看到,已经达到我们的需求,需要什么值直接匹配就OK了
数据处理基本完了。
附上一些常用的URL以及处理方式:

//设置或获取对象指定的文件名或路径。
window.location.pathname
//https://editor.csdn.net/md

//设置或获取与 URL 关联的端口号码。
let url = 'http://localhost:8086/topic/index?topicId=361'
window.location.port
//8060

//设置或获取 URL 的协议部分。
window.location.protocol
//http:

//设置或获取 href 属性中在井号“#”后面的分段。
let url = 'http://localhost:8086/topic/index#topicId=361'
window.location.hash
//#topicId=361

//设置或获取 location 或 URL 的 hostname 和 port 号码。
window.location.host
//http://localhost:8086

以上就是对于URL的常用处理方式,主要来说就是拿到需要的值参数,对参数进行处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值