做前端的,应该有不少人都写过操作URL的代码,比如提取问号后面的参数、或者主机名什么的,比如这样:
1
2
3
|
var
url
=
"http://jszai.com/foo?bar=baz"
,
separator
=
url
.
indexOf
(
'?'
)
>
-
1
?
'&'
:
'?'
;
url
+
=
separator
+
encodeURIComponent
(
"foo"
)
+
"="
+
encodeURIComponent
(
"bar"
)
;
|
这类代码写多了也觉得很烦,如果有一个比较全面的解决方案就好了。
URI.js是一个全能的操作URL的库,可以方便地提取和编辑URL中的任意一部分,而且语法优雅。
它的主要功能包括:
- URI.js支持提取和修改URL中的:协议、用户名、密码、主机名host、端口port、路径path、文件名、文件后缀、“?”后面的query(如?s=abc)、“#”后面的fragment(如#top)等
123456789var url = new URI ( "http://jszai.com/foo?bar=baz" ) ;url . host ( ) ;// => jszai.comurl . addQuery ( "hello" , "jszai" ) ;// => http://jszai.com/foo?bar=baz&hello=jszaiurl . query ( true ) ;// => { foo: "bar", hello : "jszai" } - 进行绝对路径和相对路径的计算
123var relative_path = new URI ( '../static/css/style.css' ) ;relative_path . absoluteTo ( 'http://jszai.com/hello-world' ) ;// => http://jszai.com/static/css/style.css - 清理URL(标准化)
123var uri = new URI ( "/hello/foo/woo/.././../world.html" ) ;uri . normalizePathname ( ) ; // 清理路径// uri == "/hello/world.html" - 比较URL
1234567891011var 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 ; - 如果不喜欢新建对象的使用方式,它还提供了一系列的静态的工具函数
12345678910111213141516171819var 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),至于用不用,就只能自己权衡了。
文档地址:http://medialize.github.com/URI.js/
源码地址:https://github.com/medialize/URI.js
文件大小:45KB(普通)、35KB(精简后)