首页
/ jsUri 技术文档

jsUri 技术文档

2024-12-24 23:00:10作者:盛欣凯Ernestine

1. 安装指南

1.1 通过 npm 安装

你可以通过 npm 安装 jsUri,命令如下:

npm install jsuri

1.2 在浏览器中使用

如果你需要在浏览器中使用 jsUri,可以通过下载 jsUri 的源文件并将其引入到你的 HTML 文件中:

<script src="path/to/jsuri.js"></script>

2. 项目的使用说明

2.1 创建 URI 对象

你可以通过传入一个 URL 字符串来创建一个 Uri 对象:

var uri = new Uri('http://user:pass@www.test.com:81/index.html?q=books#fragment');

2.2 获取 URI 的各个部分

jsUri 提供了多种方法来获取 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'

2.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'

2.4 链式调用

jsUri 支持链式调用,方便你组合 URI 字符串:

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'

3. 项目API使用文档

3.1 查询参数方法

3.1.1 获取第一个查询参数值

new Uri('?cat=1&cat=2&cat=3').getQueryParamValue('cat');             // 返回 '1'

3.1.2 获取所有查询参数值

new Uri('?cat=1&cat=2&cat=3').getQueryParamValues('cat');            // 返回 ['1', '2', '3']

3.1.3 添加查询参数

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'

3.1.4 替换查询参数

new Uri().replaceQueryParam('page', 2);     // 返回 '?page=2'

new Uri('?a=1&b=2&c=3')
    .replaceQueryParam('a', 'eh');          // 返回 '?a=eh&b=2&c=3'

3.1.5 删除查询参数

new Uri('?a=1&b=2&c=3')
    .deleteQueryParam('a');                 // 返回 '?b=2&c=3'

3.1.6 检查查询参数是否存在

new Uri('?a=1&b=2&c=3')
    .hasQueryParam('a');                    // 返回 true

3.2 克隆 URI 对象

你可以克隆一个 URI 对象,克隆后的对象与原对象没有共享状态:

var baseUri = new Uri('http://localhost/');

baseUri.clone().setProtocol('https');   // 返回 'https://localhost/'
baseUri                                // 返回 'http://localhost/'

4. 项目安装方式

4.1 通过 npm 安装

npm install jsuri

4.2 在浏览器中使用

<script src="path/to/jsuri.js"></script>

通过以上步骤,你可以轻松地安装和使用 jsUri 来解析和操作 URI。

登录后查看全文
热门项目推荐