返回列表 發帖

URI.js - 用 JavaScript 操作 URI、URL

來源: http://medialize.github.com/URI.js/

這是一個用來操作 URI 的函式庫,用類似 jQuery 的語法來操作,相當直覺且強大!

看看範例:
// 看看修改 URL 是多麼簡單的一件事:
URI("http://jsgears.com/foo.html?hello=world")
    .username("wmh") 
        // -> http://wmh@jsgears.com/foo.html?hello=world
    .username("") 
        // -> http://jsgears.com/foo.html?hello=world
    .directory("bar")
        // -> http://jsgears.com/bar/foo.html?hello=world
    .suffix("xml")    
        // -> http://jsgears.com/bar/foo.xml?hello=world
    .hash("tutorial")
        // -> http://jsgears.com/bar/foo.xml?hello=world#tutorial
    .fragment("")
        // -> http://jsgears.com/bar/foo.xml?hello=world
    .search("") // alias of .query()
        // -> http://jsgears.com/bar/foo.xml
    .tld("org")
        // -> http://jsgears.org/bar/foo.xml
    .search({ foo: "bar", hello: ["world", "mars"] });
        // -> http://jsgears.org/bar/foo.xml?foo=bar&hello=world&hello=mars
修改 query strings 變得超簡單:
URI("?hello=world")
    .addSearch("hello", "mars")
        // -> ?hello=world&hello=mars
    .addSearch({ foo: ["bar", "baz"] })
        // -> ?hello=world&hello=mars&foo=bar&foo=baz
    .removeSearch("hello", "mars")
        // -> ?hello=world&foo=bar&foo=baz
    .removeSearch("foo")
        // -> ?hello=world
修改路徑,超簡單:
URI("/relative/path")
    .relativeTo("/relative/sub/foo/sub/file")
        // -> ../../../path 
    .absoluteTo("/relative/sub/foo/sub/file");
        // -> /relative/path 
去蕪存菁:
URI("?&foo=bar&&foo=bar&foo=baz&")
    .normalizeSearch();
        // -> ?foo=bar&foo=baz
URI("/hello/foo/woo/.././../world.html")
    .normalizePathname();
        // -> /hello/world.html 
偵測 URI 更是簡單:
var source = "Hello jsgears.com,\n"
    + "http://google.com is a search engine, like http://www.bing.com\n"
    + "http://jsgears.com/foo.html?baz=la#bumm is an IDN URL,\n"
    + "http://123.123.123.123/foo.html is IPv4 and "
    + "http://fe80:0000:0000:0000:0204:61ff:fe9d:f156/foobar.html is IPv6.\n"
    + "links can also be in parens (http://jsgears.com) "
    + "or quotes ?http://jsgears.com?.";

var result = URI.withinString(source, function(url) {
    return '<a>' + url + '</a>';
});

/* result is:
Hello <a>jsgears.com</a>,
<a>http://google.com</a> is a search engine, like <a>http://www.bing.com</a>
<a>http://jsgears.com/foo.html?baz=la#bumm</a> is an IDN URL,
<a>http://123.123.123.123/foo.html</a> is IPv4 and <a>http://fe80:0000:0000:0000:0204:61ff:fe9d:f156/foobar.html</a> is IPv6.
links can also be in parens (<a>http://jsgears.com</a>) or quotes ?<a>http://jsgears.com</a>?.
*/
作者:Rodney Rehm
授權: MIT license 及 GPL v3
To infinity and beyond!

返回列表 回復 發帖