主题
URL
URL API 用于解析、拼接和修改网址。相比手动字符串处理,它更适合做查询参数读写、相对路径解析、资源地址拼接等工作。
创建 URL 对象
可以直接传入完整地址,也可以传入相对路径并指定基准地址。
js
const url1 = new URL('https://example.com:8080/path/list?page=1#title')
const url2 = new URL('/users?id=1', 'https://example.com')
console.log(url1.href) // https://example.com:8080/path/list?page=1#title
console.log(url2.href) // https://example.com/users?id=1常用属性
js
const url = new URL('https://example.com:8080/docs/index.html?page=2#intro')
console.log(url.origin) // https://example.com:8080
console.log(url.protocol) // https:
console.log(url.host) // example.com:8080
console.log(url.hostname) // example.com
console.log(url.port) // 8080
console.log(url.pathname) // /docs/index.html
console.log(url.search) // ?page=2
console.log(url.hash) // #intro读写查询参数
查询参数通常通过 searchParams 处理。
js
const url = new URL('https://example.com/search?q=js&page=1')
console.log(url.searchParams.get('q')) // js
url.searchParams.set('page', '2')
url.searchParams.append('tag', 'web')
url.searchParams.append('tag', 'browser')
url.searchParams.delete('q')
console.log(url.toString())
// https://example.com/search?page=2&tag=web&tag=browser常见方法
get(name):读取第一个同名参数。getAll(name):读取全部同名参数。set(name, value):设置参数,不存在则新增。append(name, value):追加同名参数。delete(name):删除指定参数。has(name):判断参数是否存在。
相对路径解析
new URL(relative, base) 可以用来计算最终资源地址,适合处理静态资源或接口地址拼接。
js
const base = 'https://example.com/docs/guide/'
console.log(new URL('../assets/logo.png', base).href)
// https://example.com/docs/assets/logo.pngObject URL
浏览器还支持通过 URL.createObjectURL() 为 Blob 或 File 生成临时地址,常用于本地预览文件。
js
const fileInput = document.querySelector('input[type=file]')
fileInput.addEventListener('change', (event) => {
const file = event.target.files?.[0]
if (!file) return
const previewUrl = URL.createObjectURL(file)
console.log(previewUrl)
})使用完成后应调用 URL.revokeObjectURL() 释放引用,避免不必要的内存占用。
js
const blobUrl = URL.createObjectURL(file)
img.src = blobUrl
img.onload = () => {
URL.revokeObjectURL(blobUrl)
}使用建议
- 需要改查询参数时,优先使用
URL和URLSearchParams,不要手动拼接字符串。 - 处理相对路径时,优先使用
new URL(relative, base),避免路径层级计算出错。 createObjectURL()适合本地预览,不等于真实网络地址。
