html打开浏览器uri,URI.js 多功能浏览器 URL 操作库 - 文章教程

这篇博客介绍了URI.js库如何帮助前端开发者更方便地处理URL。通过提供一系列API,如设置用户名、改变目录、修改文件后缀和管理查询参数,URI.js可以极大地简化URL操作。示例代码展示了如何添加查询参数、清理重复项以及处理相对路径。该库大小约为7-13KB,支持通过bower和npm进行安装,并可在Node.js和浏览器环境中使用。
摘要由CSDN通过智能技术生成

作为前端开发者,经常要操作 URL 地址,比如下面的代码:

var url = "http://example.org/foo?bar=baz";

var separator = url.indexOf('?') > -1 ? '&' : '?';

url += separator + encodeURIComponent("foo") + "=" + encodeURIComponent("bar");

通过使用 URI.js 我们可以把工作变得很简单:

var url = new URI("http://example.org/foo?bar=baz");

url.addQuery("foo", "bar");

URI.js 就是为了简化我们对 URL 的操作。

API 示例

// mutating URLs

URI("http://example.org/foo.html?hello=world")

.username("rodneyrehm")

// -> http://rodneyrehm@example.org/foo.html?hello=world

.username("")

// -> http://example.org/foo.html?hello=world

.directory("bar")

// -> http://example.org/bar/foo.html?hello=world

.suffix("xml")

// -> http://example.org/bar/foo.xml?hello=world

.query("")

// -> http://example.org/bar/foo.xml

.tld("com")

// -> http://example.com/bar/foo.xml

.query({ foo: "bar", hello: ["world", "mars"] });

// -> http://example.com/bar/foo.xml?foo=bar&hello=world&hello=mars

// cleaning things up

URI("?&foo=bar&&foo=bar&foo=baz&")

.normalizeQuery();

// -> ?foo=bar&foo=baz

// working with relative paths

URI("/foo/bar/baz.html")

.relativeTo("/foo/bar/world.html");

// -> ./baz.html

URI("/foo/bar/baz.html")

.relativeTo("/foo/bar/sub/world.html")

// -> ../baz.html

.absoluteTo("/foo/bar/sub/world.html");

// -> /foo/bar/baz.html

// URI Templates

URI.expand("/foo/{dir}/{file}", {

dir: "bar",

file: "world.html"

});

// -> /foo/bar/world.html

使用 URI.js

URI.js 在没有插件的情况下大约 7KB 的压缩重量,如果你使用所有的扩展,你最终在大约 13 kb。可以通过 bower 或者 npm 安装

# using bower

bower install uri.js

# using npm

npm install urijs

在浏览器中使用

你可以直接引入压缩版的 URI.js 文件

Node.js 和 NPM

用 npm install urijs 或添加 urijs 中的依赖项 package.json。

// load URI.js

var URI = require('urijs');

// load an optional module (e.g. URITemplate)

var URITemplate = require('urijs/src/URITemplate');

URI("/foo/bar/baz.html")

.relativeTo("/foo/bar/sub/world.html")

// -> ../baz.html

RequireJS

克隆 URI.js 存储库或使用包管理器将 URI.js 导入到您的项目中。

require.config({

paths: {

urijs: 'where-you-put-uri.js/src'

}

});

require(['urijs/URI'], function(URI) {

console.log("URI.js and dependencies: ", URI("//amazon.co.uk").is('sld') ? 'loaded' : 'failed');

});

require(['urijs/URITemplate'], function(URITemplate) {

console.log("URITemplate.js and dependencies: ", URITemplate._cache ? 'loaded' : 'failed');

});

相关链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值