解析 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