一个完整的URL由以下几部分组成:
-
协议(protocol):指定访问资源的协议,例如:http,https等。
-
主机名(hostname):指定服务器的名称或IP地址。
-
端口号(port):指定服务器使用的端口号,默认端口号为80。
-
文件路径(path):指定访问资源的路径,包括文件名。
-
请求参数(query string):在指定资源时一些参数,例如搜索关键词、页码等。
-
定位位置(fragment):用于定位资源中某个特定的片段,例如HTML文档中的某个锚点。
可以使用以下方法来解析URL的各个参数:
function parseUrl(url) {
var parser = document.createElement('a');
parser.href = url;
var protocol = parser.protocol;
var hostname = parser.hostname;
var port = parser.port;
var path = parser.pathname;
var query = parser.search;
var fragment = parser.hash;
return {
protocol: protocol,
hostname: hostname,
port: port,
path: path,
query: query,
fragment: fragment
}
}
// 示例
var url = 'https://www.example.com:8080/path/to/file.html?search=keyword&page=2#section4';
var result = parseUrl(url);
console.log(result.protocol); // 输出:https:
console.log(result.hostname); // 输出:www.example.com
console.log(result.port); // 输出:8080
console.log(result.path); // 输出:/path/to/file.html
console.log(result.query); // 输出:?search=keyword&page=2
console.log(result.fragment); // 输出:#section4