// 解析 URL 示例代码
function parseURL(url) {
// 创建一个临时的 a 标签元素
const a = document.createElement('a');
// 将传入的 URL 赋值给 a 标签的 href 属性
a.href = url;
// 返回解析后的 URL 各个部分
return {
protocol: a.protocol, // 协议,如 http:
hostname: a.hostname, // 主机名,如 www.example.com
port: a.port, // 端口,如 80 或 443
pathname: a.pathname, // 路径,如 /path/to/page
search: a.search, // 查询字符串,如 ?name=value
hash: a.hash, // 锚点,如 #section1
origin: a.origin // 原点,如 https://www.example.com
};
}
// 示例用法
const url = 'https://www.example.com/path/to/page?name=value#section1';
const parsedUrl = parseURL(url);
console.log(parsedUrl);
a
标签:通过 document.createElement('a')
创建一个临时的 <a>
元素。浏览器会自动解析赋值给 href
属性的 URL,并填充其他属性。parseURL
函数解析一个完整的 URL,并输出解析后的结果。如果需要进一步处理或提取特定部分,可以根据返回的对象进行操作。
上一篇:js urldecode
下一篇:js 编码
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站