【JS】739- JavaScript 解析 URL

https://dmitripavlutin.com/parse-url-JavaScript
1、URL 結(jié)構(gòu)

2、URL() 構(gòu)造函數(shù)
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、總結(jié)
url.search 獲取原生的 query 字符串
url.searchParams 通過 URLSearchParams 的實例去獲取具體的 query 參數(shù)
url.hostname獲取 hostname
url.pathname 獲取 pathname
url.hash 獲取 hash 值

回復(fù)“加群”與大佬們一起交流學(xué)習(xí)~
點擊“閱讀原文”查看 80+ 篇原創(chuàng)文章
評論
圖片
表情
