module--URL

url 包提供了三個(gè)方法
假設(shè)url字符串為:'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

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

按url規(guī)則拆解urlStr字符串,接收三個(gè)參數(shù)

  1. urlStr, url字符串(必傳)
  2. parseQueryString, bool類(lèi)型, 默認(rèn)值false。 對(duì)url中query部分解析后輸出格式的選擇, true的話(huà)輸出格式由默認(rèn)的 'query=string' 轉(zhuǎn)為對(duì)象格式{ query: 'string' }
  3. slashesDenoteHost, bool類(lèi)型, 默認(rèn)值false。
parse解析獲取的對(duì)象的結(jié)構(gòu),這個(gè)對(duì)認(rèn)識(shí)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的反用,將對(duì)象解析成url字符串

三、 url.resolve(from, to)

為URL或 href 插入 或 替換原有的標(biāo)簽

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);
//輸出結(jié)果:
///one/two/four
//http://example.com/one
//http://example.com/two
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容