当前位置:首页 > JavaScript

js实现路径获取

2026-03-15 19:42:22JavaScript

获取当前页面路径

使用window.location对象可以获取当前页面的完整路径或部分路径信息。以下是常用属性:

const fullPath = window.location.href;      // 完整URL(含协议、域名、路径等)
const pathname = window.location.pathname;  // 路径部分(如"/articles/123")
const origin = window.location.origin;      // 协议+域名(如"https://example.com")

获取文件绝对路径

通过URL.createObjectURL()可获取本地文件的临时路径:

js实现路径获取

const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', (e) => {
  const file = e.target.files[0];
  const filePath = URL.createObjectURL(file); // 生成blob路径
  console.log(filePath); // 输出类似 blob:https://example.com/550e8400...
});

解析URL路径参数

使用URLSearchParams解析查询字符串:

const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id'); // 获取?id=123中的123
const allParams = Object.fromEntries(urlParams.entries()); // 转为对象

Node.js路径处理

在Node.js环境中使用path模块处理文件路径:

js实现路径获取

const path = require('path');
const fullPath = path.join(__dirname, 'files', 'test.txt'); // 拼接路径
const ext = path.extname(fullPath); // 获取扩展名
const dir = path.dirname(fullPath); // 获取目录名

浏览器路由路径

前端框架中的路由路径获取示例(以React Router为例):

import { useLocation } from 'react-router-dom';
function Component() {
  const location = useLocation();
  console.log(location.pathname); // 获取当前路由路径
}

相对路径转绝对路径

将相对路径转换为绝对路径:

function toAbsoluteUrl(relativePath) {
  return new URL(relativePath, window.location.origin).href;
}
const absUrl = toAbsoluteUrl('/images/logo.png');

以上方法覆盖了浏览器环境和Node.js环境下的常见路径获取需求,根据具体场景选择合适的方式即可。

标签: 路径js
分享给朋友:

相关文章

js实现轮播图

js实现轮播图

轮播图实现方法 基础HTML结构 <div class="slider"> <div class="slides"> <img src="image1.jpg…

js实现vue路由

js实现vue路由

Vue路由基础实现 使用Vue Router实现前端路由需要先安装并配置路由库。Vue Router是Vue.js官方的路由管理器。 安装Vue Router: npm install vue-r…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现分页

js实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以直…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callback) {…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…