不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2023-07-27 00:10:12  修改时间:2024-05-11 01:17:41  分类:前端/Vue/Node.js  编辑

做前端的,应该有不少人都写过操作URL的代码,比如提取问号后面的参数、或者主机名什么的,比如这样:

var url="http://jszai.com/foo?bar=baz",
separator=url.indexOf('?') >-1?'&':'?';
url+=separator+encodeURIComponent("foo")+"="+encodeURIComponent("bar");

这类代码写多了也觉得很烦,如果有一个比较全面的解决方案就好了。

URI.js是一个全能的操作URL的库,可以方便地提取和编辑URL中的任意一部分,而且语法优雅。

 

#安装

npm install uri-js

#代码中引用

const URI = require("uri-js");

 

它的主要功能包括:

1、URI.js支持提取和修改URL中的:协议、用户名、密码、主机名host、端口port、路径path、文件名、文件后缀、“?”后面的query(如?s=abc)、“#”后面的fragment(如#top)等 

var url=new URI("http://jszai.com/foo?bar=baz");
url.host();
// => jszai.com
 
url.addQuery("hello","jszai");
// => http://jszai.com/foo?bar=baz&hello=jszai
 
url.query(true);
// => { foo: "bar", hello : "jszai" }

2、进行绝对路径和相对路径的计算

var relative_path=new URI('../static/css/style.css');
relative_path.absoluteTo('http://jszai.com/hello-world');
// => http://jszai.com/static/css/style.css

3、清理URL(标准化)

var uri=new URI("/hello/foo/woo/.././../world.html");
uri.normalizePathname();  // 清理路径
// uri == "/hello/world.html"

4、比较URL

var a="http://example.org/foo/bar.html?foo=bar&hello=world&hello=mars#fragment";
var b="http://exAMPle.org:80/foo/../foo/bar.html?foo=bar&hello=world&hello=mars#fragment";
 
a!==b;
URI(a).equals(b)===true;
 
// 比较的时候,参数的顺序不一样也没关系
b="http://example.org/foo/bar.html?hello=mars&foo=bar&hello=world&#fragment";
 
a!==b;
URI(a).equals(b)===true;

5、如果不喜欢新建对象的使用方式,它还提供了一系列的静态的工具函数

var result=URI.parse("http://example.org/foo.html");
result==={
    protocol:"http",
    username:null,
    password:null,
    hostname:"example.org",
    port:null,
    path:"/foo.html",
    query:null,
    fragment:null
};
 
var result=URI.parseQuery("?foo=bar&hello=world&hello=mars&bam=&yup");
result==={
    foo:"bar",
    hello:["world","mars"],
    bam:"",
    yup:null
};

其他特性还有更多,总之,基本上就没有想不到的功能了,但强大也是有代价的,就是源文件比较大(源代码45KB),至于用不用,就只能自己权衡了。