URL对象
URL 接口用于解析,构造,规范化和编码URL。它通过提供允许你轻松阅读和修改 URL 组件的属性来工作。通常,通过在调用 URL 的构造函数时将 URL 指定为字符串或提供相对 URL 和基本 URL 来创建新的 URL 对象。然后,你可以轻松读取 URL 的已解析组成部分或对 URL 进行更改。
1.构造函数
new URL(url)
new URL(url, base)参数:
- url:一个表示绝对或相对 URL 的
DOMString或任何具有字符串化方法的对象,如<a>或者<area>- 如果
url是相对 URL,则会将url拼接到base后面 - 如果
url是绝对 URL,则无论参数base是否存在,都将被忽略。
- 如果
- base:一个表示基准 URL 的字符串,当
url为相对 URL 时,它才会生效。如果未指定,它默认为undefined。
当url是相对url时,会拼接到base后面
const url=new URL('/abc','https://xarzhi.github.io/');
console.log(url.href) // "https://xarzhi.github.io/abc"当url是绝对url时,此时base无效
const url=new URL('https://xarzhi.github.io','https://www.baidu.conm');
console.log(url.href) // "https://xarzhi.github.io"2.实例属性
hash
一个链接中,#后面的内容(包括#)都是hash值
const url=new URL('https://xarzhi.github.io#123456');
console.log(url.hash) // #123456host
URL接口的 host 属性是一个包含主机信息(即主机名)的字符串
const url=new URL('https://xarzhi.github.io');
console.log(url.host) // xarzhi.github.io如果 URL 的端口非空,则会出现 ':',后跟 URL 的端口。
const url=new URL('https://xarzhi.github.io:8080');
console.log(url.host) // xarzhi.github.io:8080hostname
hostname是一个url的域名
const url=new URL('https://xarzhi.github.io');
console.log(url.hostname) // xarzhi.github.iohref
href 属性是包含整个 URL 的字符串。
const url=new URL('https://xarzhi.github.io:8080/test/index.html#123');
console.log(url.href) // https://xarzhi.github.io:8080/test/index.html#123origin
origin 只读属性返回一个包含所表示 URL 的来源(origin)的 Unicode 序列化形式的字符串。即协议、主机和端口(如果有的话)
具体结构因 URL 类型而异:
对于
http或httpsURL,其格式为:协议名紧接'://',随后是域名,紧接着是':',之后是端口号- 若端口号没有明确指定,则端口号为默认值80(http)或者443(https)
- 若明确指定,则为明确指定的端口值
js// http const url = new URL("http://mozilla.org"); console.log(url.origin) // https://mozilla.org const url1 = new URL("http://mozilla.org:80"); console.log(url1.origin) // https://mozilla.org const url2 = new URL("http://mozilla.org:6666"); console.log(url2.origin) // https const url3 = new URL("https://mozilla.org"); console.log(url3.origin) // https://mozilla.org const url4 = new URL("https://mozilla.org:443"); console.log(url4.origin) // https://mozilla.org const url5 = new URL("https://mozilla.org:6666"); console.log(url5.origin) // https://mozilla.org:6666对于
file:URL,其值取决于浏览器。对于
blob:URL,将使用blob:后面的 URL 的来源。例如,"blob:https://mozilla.org"将返回"https://mozilla.org"。jsconst url = new URL("blob:https://mozilla.org:443/"); console.log(url.origin); // 输出“https://mozilla.org”
password
password 属性是一个包含域名之前指定的密码的字符串
如果未设置 username属性而直接设置该属性,将导致静默失败。
const url = new URL(
"https://anonymous:flabada@developer.mozilla.org/zh-CN/docs/Web/API/URL/password",
);
console.log(url.password); // 输出“flabada”pathname
const url = new URL(
"https://developer.mozilla.org/zh-CN/docs/Web/API/URL/pathname?q=value",
);
console.log(url.pathname); // 输出“/zh-CN/docs/Web/API/URL/pathname”port
port 属性是一个表示 URL 端口号的字符串。
- 若未指定端口号或端口号为80或者443,则
port为空字符串 - 若指定端口号,则
port为指定端口号的字符串
// 使用非默认端口号的 https 协议
new URL("https://example.com:5443/svn/Repos/").port; // '5443'
// 使用非默认端口号的 http 协议
new URL("http://example.com:8080/svn/Repos/").port; // '8080'
// 使用默认端口号的 https 协议
new URL("https://example.com:443/svn/Repos/").port; // ''(空字符串)
// 使用默认端口号的 http 协议
new URL("http://example.com:80/svn/Repos/").port; // ''(空字符串)
// 没有明确端口号的 https 协议
new URL("https://example.com/svn/Repos/").port; // ''(空字符串)
// 没有明确端口号的 http 协议
new URL("https://example.com/svn/Repos/").port; // ''(空字符串)protocol
protocol 属性是代表 URL 的协议方案的字符串,包括最后的 ':'。
const url = new URL("http://mozilla.org");
console.log(url.protocol) // http:
const url1 = new URL("https://mozilla.org");
console.log(url1.protocol) // https:search
search 属性是一个搜索字符串,也称为查询字符串,这是一个包含 '?' 且其后跟着 URL 的参数的字符串。
const url = new URL("http://mozilla.org?foo=1&bar=2");
console.log(url.search) // ?foo=1&bar=2searchParams
searchParams 属性返回一个 URLSearchParams 对象(见下方),这个对象包含当前 URL 中解码后的 GET 查询参数。
const url = new URL("http://mozilla.org?foo=1&bar=2");
const searchParams = url.searchParams;
console.log(searchParams.get("foo")); // "1"
console.log(searchParams.get("bar")); // "2"username
username 属性是一个表示在域名前指定的用户名的字符串。
const url = new URL(
"https://anonymous:flabada@developer.mozilla.org/zh-CN/docs/Web/API/URL/username",
);
console.log(url.username); // 输出“anonymous”3.静态方法
URL.canParse()
URL.canParse() 静态方法返回一个布尔值,表示绝对 URL 或与基本 URL 结合的相对地址是否可解析和有效。
URL.canParse(url)
URL.canParse(url, base)参数:
- url:一个表示绝对或相对 URL 的
DOMString或任何具有字符串化方法的对象,如<a>或者<area>- 如果
url是相对 URL,则会将url拼接到base后面 - 如果
url是绝对 URL,则无论参数base是否存在,都将被忽略。
- 如果
- base:一个表示基准 URL 的字符串,当
url为相对 URL 时,它才会生效。如果未指定,它默认为undefined。
console.log(URL.canParse("https://xarzhi.github.io")) // true
console.log(URL.canParse("/zh-CN/docs","https://xarzhi.github.io")) // true
console.log(URL.canParse("/zh-CN/docs")) // falseURL.createObjectURL()
createObjectURL() 可以给指定的Blob或File对象创建一个url,从而可以在网页上展示,或者文件的下载
URL.createObjectURL(object)参数:
- object:用于创建
URL的File、Blob或MediaSource对象。
新窗口预览图片
<body>
<input type="file" id="fileInput" accept="image/*" />
<script>
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
const url=URL.createObjectURL(file);
open(url);
})
</script>
</body>TIP
每次调用 createObjectURL() 时,都会创建一个新的对象 URL,即使已经为同一个对象创建了一个 URL。当不再需要这些对象时,必须通过调用 URL.revokeObjectURL()来释放它们。
URL.revokeObjectURL()
你完成对对象 URL 的使用后,请调用此方法,让浏览器知道无需再保持对文件的引用。
const blob = new Blob(['hello world'], { type: 'text/plain' })
const url = URL.createObjectURL(blob)
URL.revokeObjectURL(url)4.实例方法
toJSON()
toJSON() 方法返回一个包含 URL 序列化版本的字符串,但实际上它似乎与 URL.toString() 的效果相同。
const url = new URL(
"https://developer.mozilla.org/zh-CN/docs/Web/API/URL/toString",
);
url.toJSON(); // 应以字符串形式返回 URLtoString()
toString() 方法返回一个包含整个 URL 的字符串。它实际上是 URL.href的只读版本。
const url = new URL(
"https://developer.mozilla.org/zh-CN/docs/Web/API/URL/toString",
);
url.toString(); // 应以字符串形式返回 URL5.URLSearchParams对象
URLSearchParams 接口定义了一些实用的方法来处理 URL 的查询字符串。
一个实现了 URLSearchParams 的对象可以直接用在 for...of 结构中,以键/值对在查询字符串中出现的顺序对它们进行迭代,例如下面两行是等价的:
for (const [key, value] of mySearchParams) {
}
for (const [key, value] of mySearchParams.entries()) {
}5.1 构造函数
返回一个 URLSearchParams 对象。
new URLSearchParams()
new URLSearchParams(options)参数:
- options:可以是以下之一:
- 一系列基于字面量的字符串键值对,或者任何对象(例如
FormData对象),能提供一系列字符串对的迭代器对象。需要注意,File将被序列化为[object File],而不是它们的文件名(就像application/x-www-form-urlencoded格式中的那样)。 - 一个由字符串键和字符串值组成的键值对对象。请注意,不支持嵌套。
- 一系列基于字面量的字符串键值对,或者任何对象(例如
// 通过 url.search 检索参数,传递到构造函数
const url = new URL("https://example.com?foo=1&bar=2");
const params1 = new URLSearchParams(url.search);
// 直接从 URL 对象获取 URLSearchParams 对象
const params1a = url.searchParams;
// 传入字符串
const params2 = new URLSearchParams("foo=1&bar=2");
const params2a = new URLSearchParams("?foo=1&bar=2");
// 传入一系列键值对
const params3 = new URLSearchParams([
["foo", "1"],
["bar", "2"],
]);
// 传入记录
const params4 = new URLSearchParams({ foo: "1", bar: "2" });5.2 实例属性
size
返回 URLSearchParams 对象中查询参数的总个数。
5.3 实例方法
append
append() 方法将指定的键/值对附加为新的查询参数。
append(name, value)参数:
- name:要附加的参数的键名。
- value:要附加的参数的值。
const url=new URL("https://www.example.com/")
const params=new URLSearchParams()
params.append("name","xarzhi")
params.append("age",18)
url.search=params.toString()
console.log(url.href) // https://www.example.com/?name=xarzhi&age=18toString
返回URLSearchParams对象中的查询字符串,不带?
const url = new URL("https://example.com?foo=1&bar=2");
const params = new URLSearchParams(url.search);
// 添加第二个参数。
params.append("foo", 4);
console.log(params.toString()); // 输出“foo=1&bar=2&foo=4”delete
delete() 方法从所有查询参数的列表中删除指定的参数及其关联值。
delete(name)
delete(name, value)参数:
- name:需要删除的键值名称。
- value:可选参数必须匹配的值以及要删除的给定名称。
删除指定名称的所有参数
const url = new URL("https://example.com?foo=1&bar=2&foo=3");
const params = new URLSearchParams(url.search);
console.log(params); // foo=1&bar=2&foo=3
params.delete("foo");
console.log(params); // bar=2删除指定名称和值的所有参数
const url = new URL("https://example.com?foo=1&bar=2&foo=3&foo=1");
const params = new URLSearchParams(url.search);
console.log(params); // foo=1&bar=2&foo=3&foo=1
params.delete("foo", "1");
console.log(params); // bar=2&foo=3entries
entries() 方法返回一个用于遍历该对象中包含的所有键/值对的迭代器。迭代器按照查询字符串中出现的顺序返回键/值对,每一组键和值都是字符串对象。
// 创建一个测试用的 URLSearchParams 对象
const searchParams = new URLSearchParams("key1=value1&key2=value2");
// 显示键/值对
for (const [key, value] of searchParams.entries()) {
console.log(`${key}, ${value}`);
}
/*
key1, value1
key2, value2
*/forEach
forEach() 方法允许通过回调函数来遍历实例对象上的键值对。类似于数组的forEach()
forEach(callback)
forEach(callback, thisArg)参数:
- callback在每个元素上执行的函数,会传入以下参数:
- value:URLSearchParams 对象中正在处理的条目的值。
- key:URLSearchParams 对象中正在处理的条目的键。
- searchParams:当前调用 forEach() 方法的 URLSearchParams 对象。
- thisArg 可选执行 callback 时 this 的值。
const searchParams = new URLSearchParams("key1=value1&key2=value2");
searchParams.forEach((value, key) => {
console.log(value, key);
});
/*
value1 key1
value2 key2
*/get
get() 方法返回第一个与查询参数对应的值。
get(name)参数:
- name:要返回的参数的键名。
返回值:如果找到了给定的查询参数,则返回查找到的字符串;否则返回 null。
const url = new URL('https://example.com?foo=1&bar=2&foo=3')
const params = url.searchParams
console.log(params.get('foo')) // "1"getAll
getAll() 方法以数组的形式返回与指定查询参数对应的所有值。
getAll(name)参数:
- name:要返回的参数的键名。
返回值:一个数组,包含符合条件的所有值,若没有复合的值则为空数组
const url = new URL('https://example.com?foo=1&bar=2&foo=3')
const params = url.searchParams
console.log(params.getAll('foo')) // ['1','3']has
has() 方法返回一个布尔值,表示指定的键名对应的值是否存在于查询参数中。
has(name)
has(name, value)参数
- name:要匹配的参数的名称。
- value:要匹配的参数值以及给定的名称。
返回值:一个布尔值。
- 若只传入一个
name,则只要有一个符合name的键,则返回true,否则为false - 若传入了
name和value,则查找是否有和name与value相对于的键值对,有为true,否则为false
const url = new URL('https://example.com?foo=1&bar=2&foo=3')
const params = url.searchParams
console.log(params.has('foo')) // true
console.log(params.has('foo', 1)) // true
console.log(params.has('foo', 66)) // false
console.log(params.has('abc', 66)) // falsekeys
keys() 方法返回一个用于遍历对象中包含的所有键的迭代器。这些键都是字符串对象。
// 建立一个测试用 URLSearchParams 对象
const searchParams = new URLSearchParams("key1=value1&key2=value2");
// 输出键值对
for (const key of searchParams.keys()) {
console.log(key);
}values
values() 方法返回一个用于遍历对象中包含的所有值的迭代器。这些键都是字符串对象。
const searchParams = new URLSearchParams("key1=value1&key2=value2");
for (const value of searchParams.values()) {
console.log(value);
}
/*
value1
value2
*/set
set() 方法用于给URlSearchParams对象添加指定的键值对
- 若指定的键对不存在,则添加
- 若指定的键已存在,则修改值
- 若指定的键已存在多个,重复的会被删掉,并且添加此次这个新的键值对
set(name, value)参数:
- name:要设置的参数的键名。
- value:要设置的参数的值。
// 建立一个测试用 URLSearchParams 对象
const searchParams = new URLSearchParams('key1=value1&key2=value2&key2=777')
// 添加一个新的键值对
searchParams.set('key3', 'value3')
console.log(searchParams.toString()) // key1=value1&key2=value2&&key2=777&key3=value3
// 修改一个键值对的值
searchParams.set('key2', '666')
console.log(searchParams.toString()) // key1=value1&key2=666&key3=value3sort
URLSearchParams.sort() 方法对包含在此对象中的所有键/值对进行排序,排序顺序是根据键的 Unicode 码位。该方法使用稳定的排序算法(即,将保留具有相等键的键/值对之间的相对顺序)。
// 创建一个测试用的 URLSearchParams 对象
const searchParams = new URLSearchParams("c=4&a=2&b=3&a=1");
// 对键/值对进行派寻
searchParams.sort();
// 显示排序后的查询字符串
console.log(searchParams.toString()); // a=2&a=1&b=3&c=4