Cách đơn giản, chuẩn và không cần regex: tạo element <a> tạm, gán href, trình duyệt tự parse thành các property.
Cách làm (DOM Method)
<script>
function parseURL(url) {
const parser = document.createElement('a');
parser.href = url;
return {
protocol: parser.protocol, // "https:"
host: parser.host, // "www.example.com:8080"
hostname: parser.hostname, // "www.example.com"
port: parser.port, // "8080" (rỗng nếu default)
pathname: parser.pathname, // "/path/to/page"
search: parser.search, // "?query=string"
hash: parser.hash, // "#fragment"
origin: parser.origin // "https://www.example.com:8080"
};
}
const result = parseURL("https://www.youtube.com/watch?v=tNJJSrfKYwQ");
document.write(JSON.stringify(result, null, 2));
</script>
Kết quả
{
"protocol": "https:",
"host": "www.youtube.com",
"hostname": "www.youtube.com",
"port": "",
"pathname": "/watch",
"search": "?v=tNJJSrfKYwQ",
"hash": "",
"origin": "https://www.youtube.com"
}
URL API (Modern, ES2015+) — Khuyên dùng
const url = new URL("https://user:pass@www.example.com:8080/path?query=1#hash");
console.log(url.protocol); // "https:"
console.log(url.hostname); // "www.example.com"
console.log(url.port); // "8080"
console.log(url.pathname); // "/path"
console.log(url.search); // "?query=1"
console.log(url.hash); // "#hash"
console.log(url.username); // "user"
console.log(url.password); // "pass"
console.log(url.searchParams.get('query')); // "1" — tiện xử lý query string
So sánh
| Phương pháp | Ưu điểm | Nhược điểm |
|---|---|---|
<a> element | Đơn giản, chạy IE11+ | Không có searchParams, không validate URL |
new URL() | Chuẩn WHATWG, có searchParams, validation, setter | Cần polyfill cho IE, throw nếu URL invalid |
| Regex | Kiểm soát hoàn toàn | Phức tạp, dễ sai, maintain khó |
Lưu ý
new URL()throw error nếu URL không hợp lệ — dùngtry/catch.- Relative URL:
new URL('/path', 'https://base.com'). - Node.js:
require('url').parse()(legacy) hoặcnew URL()(v10+).