当前位置:首页 > JavaScript

js实现url

2026-04-07 04:59:46JavaScript

js实现url

使用 JavaScript 处理 URL

JavaScript 提供了 URLURLSearchParams 对象,可以方便地解析、构造和操作 URL。

js实现url

解析 URL

const url = new URL('https://example.com/path?name=value#hash');

console.log(url.href);      // 完整 URL
console.log(url.origin);    // 协议 + 域名 + 端口
console.log(url.protocol);  // 协议 (https:)
console.log(url.host);      // 域名 + 端口
console.log(url.hostname);  // 域名
console.log(url.port);      // 端口
console.log(url.pathname);  // 路径 (/path)
console.log(url.search);    // 查询字符串 (?name=value)
console.log(url.hash);      // 哈希 (#hash)

操作查询参数

const url = new URL('https://example.com?foo=bar&baz=qux');

// 获取参数
console.log(url.searchParams.get('foo')); // "bar"

// 设置参数
url.searchParams.set('foo', 'newvalue');

// 添加参数
url.searchParams.append('new', 'param');

// 删除参数
url.searchParams.delete('baz');

// 转换为字符串
console.log(url.toString()); 
// "https://example.com/?foo=newvalue&new=param"

构造 URL

const url = new URL('https://example.com');
url.pathname = '/new/path';
url.searchParams.set('param', 'value');
console.log(url.href); 
// "https://example.com/new/path?param=value"

处理相对 URL

const base = 'https://example.com/base/';
const relative = '../path';
const absolute = new URL(relative, base).href;
console.log(absolute); // "https://example.com/path"

兼容性注意事项

现代浏览器都支持 URLURLSearchParams API。对于旧版浏览器,可能需要使用 polyfill 或手动解析 URL 字符串。

手动解析 URL 的正则表达式方法

function parseUrl(url) {
  const pattern = /^(https?:\/\/)?([^\/\?:]+)(:(\d+))?([^?#]*)(\?([^#]*))?(#(.*))?/;
  const matches = url.match(pattern);

  return {
    protocol: matches[1] || '',
    host: matches[2] || '',
    port: matches[4] || '',
    path: matches[5] || '',
    query: matches[7] || '',
    hash: matches[9] || ''
  };
}

标签: jsurl
分享给朋友:

相关文章

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js实现延迟

js实现延迟

实现延迟的方法 在JavaScript中,实现延迟操作有多种方式,以下是几种常见的方法: 使用setTimeout函数 setTimeout是JavaScript中最常用的延迟执行方法。它接受一个回…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数: fun…

js实现按钮点击

js实现按钮点击

实现按钮点击的JavaScript方法 HTML按钮元素 在HTML中创建按钮元素,为其添加id或class以便JavaScript选择: <button id="myButton">点…