【JS】739- JavaScript 解析 URL
前端自习课
共 4382字,需浏览 9分钟
· 2020-10-10
https://dmitripavlutin.com/parse-url-JavaScript
1、URL 结构
![](https://filescdn.proginn.com/bf35e5eed569ee7c793e8e5f10e95a73/5c82705bbe6fb8a1b589892e52ca57d4.webp)
2、URL() 构造函数
const url = new URL(relativeOrAbsolute [, absoluteBase]);
const url = new URL('http://example.com/path/index.html');
url.href; // => 'http://example.com/path/index.html'
const url = new URL('/path/index.html', 'http://example.com');
url.href; // => 'http://example.com/path/index.html'
interface URL {
href: USVString;
protocol: USVString;
username: USVString;
password: USVString;
host: USVString;
hostname: USVString;
port: USVString;
pathname: USVString;
search: USVString;
hash: USVString;
readonly origin: USVString;
readonly searchParams: URLSearchParams;
tojsON(): USVString;
}
3、Query 字符串
const url = new URL(
'http://example.com/path/index.html?message=hello&who=world'
);
url.search; // => '?message=hello&who=world'
const url1 = new URL('http://example.com/path/index.html');
const url2 = new URL('http://example.com/path/index.html?');
url1.search; // => ''
url2.search; // => ''
3.1 、解析 query 字符串
const url = new URL(
'http://example.com/path/index.html?message=hello&who=world'
);
url.searchParams.get('message'); // => 'hello'
url.searchParams.get('missing'); // => null
4、hostname
const url = new URL('http://example.com/path/index.html');
url.hostname; // => 'example.com'
5、pathname
const url = new URL('http://example.com/path/index.html?param=value');
url.pathname; // => '/path/index.html'
const url = new URL('http://example.com/');
url.pathname; // => '/'
6、hash
const url = new URL('http://example.com/path/index.html#bottom');
url.hash; // => '#bottom'
const url = new URL('http://example.com/path/index.html');
url.hash; // => ''
7、URL 校验
try {
const url = new URL('http ://example.com');
} catch (error) {
error; // => TypeError, "Failed to construct URL: Invalid URL"
}
8、修改 URL
const url = new URL('http://red.com/path/index.html');
url.href; // => 'http://red.com/path/index.html'
url.hostname = 'blue.io';
url.href; // => 'http://blue.io/path/index.html'
9、总结
url.search 获取原生的 query 字符串
url.searchParams 通过 URLSearchParams 的实例去获取具体的 query 参数
url.hostname获取 hostname
url.pathname 获取 pathname
url.hash 获取 hash 值
回复“加群”与大佬们一起交流学习~
点击“阅读原文”查看 80+ 篇原创文章
评论
VSiteParser在线视频URL解析
VSiteParser是一个可以把在线视频URL解析成swf地址的js模块。而它不仅可以用于前端,也可以在node.js上面使用.只需要安装npm包( npminstallvsiteparser)即可
VSiteParser在线视频URL解析
0
oneurlC/C++的URL解析库
oneurl是一个C/C++语言开发的url解析以及标准化开源库,基于googleurl内核函数,主要功能:a.解析url,可以得到协议(scheme),主机名(host),端口(port),域名(D
oneurlC/C++的URL解析库
0
CSVjsCSV 的 JavaScript 解析库
CSVjs 是一个使用纯 JavaScript 实现对 CSV 内容的编解码的库。示例代码:var
CSVjsCSV 的 JavaScript 解析库
0