JS【详解】内置构造函数/对象 URL(可用于创建和解析 URL,操作搜索参数,编码 url)

用途

用于创建和解析 URL

语法

dos 复制代码
new URL(url, [base])
  • 第1个参数 url :可为完整 url 或路径(如果设置了 base)
  • 第2个参数 base:可选的 base URL,若第1个参数是路径,则会根据这个 base 生成 URL
js 复制代码
new URL('https://www.baidu.com/admin') // https://www.baidu.com/admin

new URL('/admin', 'https://www.baidu.com') // https://www.baidu.com/admin

更多用法

根据现有 URL 创建一个新的 URL

js 复制代码
let url = new URL('https://www.baidu.com/admin');
let newUrl = new URL('login', url);
 
console.log(newUrl); // https://www.baidu.com/login

解析 url

js 复制代码
let url = new URL('https://www.baidu.com/admin');
 
console.log(url.protocol); // https:
console.log(url.host);     // www.baidu.com
console.log(url.pathname); // /admin

操作搜索参数

  • append(name, value) ------ 按照 name 添加参数,
  • delete(name) ------ 按照 name 移除参数,
  • get(name) ------ 按照 name 获取参数,
  • getAll(name) ------ 获取相同 name 的所有参数(这是可行的,例如 ?user=John&user=Pete),
  • has(name) ------ 按照 name 检查参数是否存在,
  • set(name, value) ------ set/replace 参数,
  • sort() ------ 按 name 对参数进行排序,很少使用
js 复制代码
let url = new URL('https://www.baidu.com/search');
url.searchParams.set('q', 'test me!'); // 添加带有一个空格和一个 ! 的参数
 
console.log(url); // https://www.baidu.com/search?q=test+me%21
 
url.searchParams.set('tbs', 'qdr:y'); // 添加带有一个冒号 : 的参数
 
// 参数会被自动编码
console.log(url); // https://www.baidu.com/search?q=test+me%21&tbs=qdr%3Ay
 
// 遍历搜索参数(被解码)
for(let [name, value] of url.searchParams) {
  console.log(`${name}=${value}`); // q=test me!,然后是 tbs=qdr:y
}

编码 url

许多字符不允许直接在 URL 中使用,如大写字母和空格等,需编码为UTF-8

js 复制代码
// 在此示例中使用一些西里尔字符
let url = new URL('https://www.baidu.com/wiki/Тест');
url.searchParams.set('key', 'ъ');
 
console.log(url); //https://www.baidu.com/wiki/%D0%A2%D0%B5%D1%81%D1%82?key=%D1%8A
相关推荐
摘星编程7 小时前
React Native for OpenHarmony 实战:Linking 链接处理详解
javascript·react native·react.js
胖者是谁7 小时前
EasyPlayerPro的使用方法
前端·javascript·css
EndingCoder7 小时前
索引类型和 keyof 操作符
linux·运维·前端·javascript·ubuntu·typescript
摘星编程8 小时前
React Native for OpenHarmony 实战:ImageBackground 背景图片详解
javascript·react native·react.js
摘星编程9 小时前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe5569 小时前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
WHS-_-20229 小时前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
摘星编程9 小时前
React Native for OpenHarmony 实战:GestureResponderSystem 手势系统详解
javascript·react native·react.js
lili-felicity9 小时前
React Native for OpenHarmony 实战:加载效果的实现详解
javascript·react native·react.js·harmonyos
济61710 小时前
linux 系统移植(第六期)--Uboot移植(5)--bootcmd 和 bootargs 环境变量-- Ubuntu20.04
java·前端·javascript