在前端开发中,处理 URL 是一项常见任务。围绕这个问题,npm 社区提供了许多工具包,其中一个非常流行的包是 blear.utils.uri。
安装
安装 blear.utils.uri 可以使用 npm:
npm install blear.utils.uri --save
将 package.json 的 dependencies 项更新为:
"dependencies": { "blear.utils.uri": "^1.0.0" }
基本用法
有了 blear.utils.uri 就可以简单地解析 URL。具体使用方式如下:
const uri = require('blear.utils.uri') const params = uri.parseParams('https://www.example.com/page?id=123&name=example') console.log(params.id) // 123 console.log(params.name) // example
解析出来的参数是一个对象,它有和 URL 中参数名一致的属性。如果 URL 中有多个同名参数,那么它们会被合并为一个数组。如果参数不是通过 ? 号连接在 URL 后面,可以使用另一个方法来解析:
const params = uri.parseParams('https://www.example.com/some/path?a=123&b=example', 'a', 'b') console.log(params.a) // 123 console.log(params.b) // example
此时需要显式传递参数名。
进阶用法
除了解析参数,blear.utils.uri 还提供了一些实用的 URL 操作方法。
更改参数
可以通过 uri.changeParams
方法更改 URL 的参数:
const newUrl = uri.changeParams('https://www.example.com/page?id=123&name=example', { id: null, // 删除 id 参数 age: 20, // 添加 age=20 参数 }) console.log(newUrl) // 'https://www.example.com/page?name=example&age=20'
提取路径
可以通过 uri.getPath
方法提取路径:
const path = uri.getPath('https://www.example.com/page?id=123&name=example') console.log(path) // '/page'
解析域名
可以通过 uri.parseDomain
方法解析域名:
const domain = uri.parseDomain('https://www.example.com/page?id=123&name=example') console.log(domain) // 'www.example.com'
删除查询参数
可以通过 uri.removeParams
方法删除 URL 的某些查询参数:
const newUrl = uri.removeParams('https://www.example.com/page?id=123&name=example&size=large', ['id', 'size']) console.log(newUrl) // 'https://www.example.com/page?name=example'
保留查询参数
可以通过 uri.keepParams
方法保留 URL 的某些查询参数:
const newUrl = uri.keepParams('https://www.example.com/page?id=123&name=example&size=large', ['id', 'size']) console.log(newUrl) // 'https://www.example.com/page?id=123&size=large'
指导意义
blear.utils.uri 提供了一组方便实用的 URL 操作方法,可以简化前端开发中常见的 URL 处理任务。当我们需要处理 URL 时可以考虑使用该工具包,它可以提高开发效率。
同时,本文也讲解了 npm 包的安装和基本使用流程,这可以帮助初学者快速上手使用 npm 包。
示例代码
完整的示例代码如下:
-- -------------------- ---- ------- ----- --- - -------------------------- ----- --- - ------------------------------------------------------------- ----- ------ - -------------------- ---------------------- -- --- ------------------------ -- ------- ------------------------ -- ----- ----- ------- - --------------------- - --- ----- -- -- -- -- ---- --- -- -- ------ -- -- -------------------- -- -------------------------------------------------- ----- ---- - ---------------- ----------------- -- ------- ----- ------ - -------------------- ------------------- -- ----------------- ----- ------- - --------------------- ------ -------- -------------------- -- ------------------------------------------- ----- ------- - ------------------- ------ -------- -------------------- -- ------------------------------------------------展开代码
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/74273