您的位置:首页 > Web前端 > Node.js

url及node.js url模块随笔

2017-08-14 15:02 246 查看
在将url之前先附上一张图,对url的结构有个清晰的认识


这就是url清晰的组成。

接下来咱们来看一下在前端常常用到的方法

例如

var url = ‘https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=url%E6%96%87%E6%A1%A3‘,

我们想获得ie的值,怎么做呢?

下面是我封装的函数

function html_name(name) {

html = window.location.search;
arr_html = html.split("?");
if(arr_html.length > 1) {
arr_html = arr_html[1].split("&");

for(i = 0; i < arr_html.length; i++) {
arr_b = arr_html[i].split("=");
if(arr_b[0] == name) {
return arr_b['1'];
break;
}

}

return '';
} else
return '';


}

var ie = decodeURI(html_name(‘ie’));

var wd = decodeURI(html_name(‘wd’));

拿来直接调用就行

接下来来说一下在node.js中url常用的几种方法,毕竟node也算是我的一个本命英雄啦!!!!

第一招:化无形为有形

var url = require(“url”);

var burl = “https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=urlbb

var ourl =url.parse(burl);

获得其各部分的值可以直接调用

如ourl.protocol

ourl.pathname等等

第二招:万剑归宗

var obj= {

protocol: ‘https:’,

slashes: true,

auth: null,

host: ‘example.org:81’,

port: ‘81’,

hostname: ‘example.org’,

hash: null,

search: null,

query: null,

pathname: ‘/foo’,

path: ‘/foo’,

href: ‘https://example.org:81/foo’ };

var tts = url.format(obj);

console.log(tts);

第3招:移花接木

url.resolve(from,to);

如:

url.resolve(“https://example.org:81/foo“,”fou”);

url.resolve(“https://example.org:81/foo/a“,”b”);

url.resolve(“https://example.org:81/foo/a/“,”b”);

打印出来结果分别为:

https://example.org:81/fou

https://example.org:81/foo/b

https://example.org:81/foo/a/b

简而言之,就是将最后一个“/”后面的字符替换。

好吧!真编不下去啦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  url 前端 node.js