js url的处理

解析 URL的方法:

1.使用 URL 类

例如:

const url = new URL('https://www.example.com/path/to/page?query=param#hash')
console.log(url.protocol) // 输出:https:
console.log(url.host) // 输出:www.example.com
console.log(url.pathname) // 输出:/path/to/page
console.log(url.search) // 输出:?query=param
console.log(url.hash) // 输出:#hash

2.使用正则表达式

例如:

const url = 'https://www.example.com/path/to/page?query=param#hash'
const matches = url.match(/^(https?):\/\/([^\/?#]+)(?:[\/?#]|$)/i)
console.log(matches[1]) // 输出:https
console.log(matches[2]) // 输出:www.example.com

3.使用 document.createElement 方法

例如:

const url = 'https://www.example.com/path/to/page?query=param#hash'
const a = document.createElement('a')
a.href = url
console.log(a.protocol) // 输出:https:
console.log(a.host) // 输出:www.example.com
console.log(a.pathname) // 输出:/path/to/page
console.log(a.search) // 输出:?query=param
console.log(a.hash) // 输出:#hash

获取search中的参数

例如,假设你有一个 URL:

const url = new URL('https://www.example.com/path/to/page?name=John&age=30#hash')

1.使用 searchParams 属性来获取 search 中的参数

例如:

console.log(url.searchParams.get('name')) // 输出:John
console.log(url.searchParams.get('age')) // 输出:30

2.使用 forEach 方法遍历所有的参数

例如:

url.searchParams.forEach((value, key) => {
  console.log(`${key}: ${value}`)
})

输出结果如下:

name: John
age: 30

3.使用 set 方法来设置参数的值,使用 append 方法来添加新的参数,使用 delete 方法来删除参数

例如:

url.searchParams.set('name', 'Jane')
console.log(url.searchParams.get('name')) // 输出:Jane

url.searchParams.append('hobby', 'swimming')
console.log(url.searchParams.getAll('hobby')) // 输出:['swimming']

url.searchParams.delete('age')
console.log(url.searchParams.has('age')) // 输出:false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值