URL 接口提供了用于操作URL的相关方法,通过该接口,可以创建URL,获取或更改URL的host、search、hash等,URL还能自动对URL中的组件进行编码。
以如下URL为示例:
http://zhangsan:password@example.com:8080/doc/note?id=88&name=first#h1
URL细分为
其中,
http://zhangsan:password@example.com:8080/doc/note?id=88&name=first#h1
可以通过 URL 构造函数创建一个URL对象,语法如下:
url = new URL(url, [base])
构造函数有两个参数:
var url = new URL('http://example.com:8080/doc/note?id=88&name=first#h1');
使用相对 url 时,第一个参数可以传入类似 /a 、 ./a 和 ../a 的格式,下面给出几个例子。
var url = new URL('/user', 'http://baidu.com/doc/list');
console.log(url.href) // http://baidu.com/user
var url = new URL('./user', 'http://baidu.com/doc/list');
console.log(url.href) // http://baidu.com/doc/user
var url = new URL('../user', 'http://baidu.com/doc/list/v1');
console.log(url.href) // http://baidu.com/doc/user
var url = new URL('../../user', 'http://baidu.com/doc/list/v1');
console.log(url.href) // http://baidu.com/user
var url = new URL('//kuaishou.com', 'http://baidu.com/doc/list/v1');
console.log(url.href) // http://kuaishou.com
对应URL的各组成部分,一个URL实例共有12个属性:
运行如下代码可以看到对应的属性值
var url2 = new URL('http://zhangsan:password@example.com:8080/doc/note?id=88&name=first#h1');
如下图:
var url = new URL('http://baidu.com/a/b')
url.pathname = '给我编码'
console.log(url.pathname)
"/%E7%BB%99%E6%88%91%E7%BC%96%E7%A0%81"
页面更新:2024-06-04
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号