module--URL

url 包提供了三个方法
假设url字符串为:'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

一、url.parse(urlStr, [parseQueryString], [slashesDenoteHost])

按url规则拆解urlStr字符串,接收三个参数

  1. urlStr, url字符串(必传)
  2. parseQueryString, bool类型, 默认值false。 对url中query部分解析后输出格式的选择, true的话输出格式由默认的 'query=string' 转为对象格式{ query: 'string' }
  3. slashesDenoteHost, bool类型, 默认值false。
parse解析获取的对象的结构,这个对认识url的组成也是极好的:

href: The full URL that was originally parsed. Both the protocol and host are lowercased.

  Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

protocol: The request protocol, lowercased.

  Example: 'http:'

slashes: The protocol requires slashes after the colon

  Example: true or false

host: The full lowercased host portion of the URL, including port information.

  Example: 'host.com:8080'

auth: The authentication information portion of a URL.

  Example: 'user:pass'

hostname: Just the lowercased hostname portion of the host.

 Example: 'host.com'

port: The port number portion of the host.

  Example: '8080'

pathname: The path section of the URL, that comes after the host and before the query, including the initial slash if present.

  Example: '/p/a/t/h'

search: The 'query string' portion of the URL, including the leading question mark.

  Example: '?query=string'

path: Concatenation of pathname and search.

  Example: '/p/a/t/h?query=string'

query: Either the 'params' portion of the query string, or a querystring-parsed object.

  Example: 'query=string' or {'query':'string'}

hash: The 'fragment' portion of the URL including the pound-sign.

  Example: '#hash'

二、 url.format(urlObj)

parse的反用,将对象解析成url字符串

三、 url.resolve(from, to)

为URL或 href 插入 或 替换原有的标签

var url = require('url');
var a = url.resolve('/one/two/three', 'four') ,
b = url.resolve('http://example.com/', '/one'),
c = url.resolve('http://example.com/one', '/two');
console.log(a +","+ b +","+ c);
//输出结果:
///one/two/four
//http://example.com/one
//http://example.com/two
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容