jsuri 用于操作url的js开源库

Github: https://github.com/derek-watson/jsUri

针对node.js和浏览器的uri解析

// 1. 将一个uri解析为js对象
var uri = new Uri('http://user:pass@www.test.com:81/index.html?q=books#fragment');

// 2. 使用uri属性方法获取uri的每一个部分
uri.protocol()    // http
uri.userInfo()    // user:pass
uri.host()        // www.test.com
uri.port()        // 81
uri.path()        // /index.html
uri.query()       // q=books
uri.anchor()      // fragment

// 3. 使用uri属性方法修改uri的每一个部分
uri.protocol('https')
uri.toString()    // https://user:pass@www.test.com:81/index.html?q=books#fragment
uri.host('mydomain.com')
uri.toString()    // https://user:pass@mydomain.com:81/index.html?q=books#fragment

// 4. 支持链式创建修改uri,使用setter方法
new Uri()
    .setPath('/archives/1979/')
    .setQuery('?page=1')                   // /archives/1979?page=1
new Uri()
    .setPath('/index.html')
    .setAnchor('content')
    .setHost('www.test.com';)
    .setPort(8080)
    .setUserInfo('username:password')
    .setProtocol('https')
    .setQuery('this=that&some=thing')      // https://username:password@www.test.com:8080/index.html?this=that&some=thing#content
new Uri('http://www.test.com';)
    .setHost('www.yahoo.com';)
    .setProtocol('https')                  // https://www.yahoo.com

// 5. 获取属性对应的值
new Uri('?cat=1&cat=2&cat=3').getQueryParamValue('cat')             //  结果为 1
new Uri('?cat=1&cat=2&cat=3').getQueryParamValues('cat')            // 结果为数组 [1, 2, 3]
new Uri('?a=b&c=d').query().params                              //  结果为二维数组[ ['a', 'b'], ['c', 'd']]

// 6. 添加参数键值对
new Uri().addQueryParam('q', 'books')               // ?q=books
new Uri('http://www.github.com';)
    .addQueryParam('testing', '123')
    .addQueryParam('one', 1)                        // http://www.github.com/?testing=123&one=1
// insert param at index 0
new Uri('?b=2&c=3&d=4').addQueryParam('a', '1', 0)  // ?a=1&b=2&c=3&d=4

// 7. 替换参数值
new Uri().replaceQueryParam('page', 2)     // ?page=2
new Uri('?a=1&b=2&c=3')
    .replaceQueryParam('a', 'eh')          // ?a=eh&b=2&c=3
new Uri('?a=1&b=2&c=3&c=4&c=5&c=6')
    .replaceQueryParam('c', 'five', '5')   // ?a=1&b=2&c=3&c=4&c=five&c=6

// 8. 删除某个参数
new Uri('?a=1&b=2&c=3')
    .deleteQueryParam('a')                 // ?b=2&c=3
new Uri('test.com?a=1&b=2&c=3&a=eh')
    .deleteQueryParam('a', 'eh')           // test.com/?a=1&b=2&c=3

// 9. 判断uri是否包含这个参数
new Uri('?a=1&b=2&c=3')
    .hasQueryParam('a')                    // true
new Uri('?a=1&b=2&c=3')
    .hasQueryParam('d')                    // false

// 10. 克隆并修改某个uri,比如将该uri克隆一个新的https协议的uri(而不是修改本身的uri)
var baseUri = new Uri('http://localhost/';)
baseUri.clone().setProtocol('https')   // https://localhost/
baseUri                                // http://localhost/

最后更新于