# URL Common methods in node parsing

Source: Internet
Author: User

A URL string is a structured string that consists of several meaningful parts. We will inevitably use one of these parts in our work, the most primitive method of using string interception and regular matching is not easy and beautiful, so we provide a module URL for processing and parsing URLs in our Nodejs. This module provides some useful functions to make our resolution more convenient and quick, then we will analyze the use of the common functions it provides

The URL module provides two sets of APIs to handle URLs:
One is the unique API left by node. JS,

Reason for retention: Although the unique API left by node. JS is not deprecated, it is reserved for backwards compatibility with existing applications. Therefore, the new application uses the WHATWG API.

The other is usually the API that implements the WHATWG URL standard in a Web browser. The API is formally applied in the node8.0.0

In the browser, the WHATWG URL is always available globally, and in node. js, in any case, opening or using a link must refer to the ' URL ' module in advance: Require (' URL '). Url

const url = require(‘url‘);
First, let's take a look at the methods in this module.
let http = require(‘http‘);let url = require(‘url‘);console.log(url);// { Url: [Function: Url],//     parse: [Function: urlParse],//     resolve: [Function: urlResolve],//     resolveObject: [Function: urlResolveObject],//     format: [Function: urlFormat],//     URL: [Function: URL],//     URLSearchParams: [Function: URLSearchParams],//     domainToASCII: [Function: domainToASCII],//     domainToUnicode: [Function: domainToUnicode] }
And then we're going to explain how these methods are used.
let {parse, resolve, format, URL, URLSearchParams, domainToASCII, domainToUnicode} = require(‘url‘);
1. Parse (urlstr,querystring,analysishost)

Unique API left by node. js
Parameters:

URLSTR: URL address to resolve
QueryString: Parsed query string or query object, True is the object false is a string, for example: http://foo/bar?a=123, True if query: {a:123}, False if query: ' a=123 ' Default is False
Analysishost: Do you want to parse out the host (the string that is going//after to the next/previous), for example://foo/bar will be parsed as {host: ' foo ', pathname: '/bar}, otherwise {pathname: '//foo/ Bar '}. Default is False

Function: Parse URL, return a URL Property object

For example:

const myURLA =    url.parse(‘https://user:[email protected]:8080/p/a/t/h?query=string#hash‘, true);console.log(myURLA);// Url {//     protocol: ‘https:‘, // 协议//         slashes: true,//         auth: ‘user:pass‘, // 用户名密码//         host: ‘sub.host.com:8080‘, // host主机名//         port: ‘8080‘, // 端口号//         hostname: ‘sub.host.com‘, // 主机名不带端口号//         hash: ‘#hash‘, // 哈希值//         search: ‘?query=string‘,// 查询字符串//         query: ‘query=string‘, // 请求参数//         pathname: ‘/p/a/t/h‘, // 路径名//         path: ‘/p/a/t/h?query=string‘, // 带查询的路径名//         href: ‘https://user:[email protected]:8080/p/a/t/h?query=string#hash‘ // 原字符串本身}

Error:

If Urlstr is not a string, it will throw typeerror.

const myurl = url.parse({a:123});TypeError: Parameter "url" must be a string, not object

Throws Urierror if the Auth property exists but cannot be encoded.

2, resolve (from, to)

Parameters:

From: Basic URL for parsing
To: The URL of the hyperlink to parse

function: Resolves a destination URL to a base URL in a way that a Web browser parses a hyperlink.

For example:

const url = require(‘url‘);url.resolve(‘/one/two/three‘, ‘four‘);         // ‘/one/two/four‘url.resolve(‘http://example.com/‘, ‘/one‘);    // ‘http://example.com/one‘url.resolve(‘http://example.com/one‘, ‘/two‘); // ‘http://example.com/two‘
3. Format (url,options)

Parameters:

URL: An WHATWG URL object
Options
1. Auth: If the serialized URL string should contain a user name and a password of true, otherwise false. The default is true.
2. Fragment: False if the serialized URL string should contain a fragment of true. The default is true. That is, if you need to include a hash value
3. Search: False if the serialized URL string should contain a search query of true. The default is true.
4. Unicode:true if the Unicode character that appears in the URL string host element should be encoded directly instead of using Punycode encoding to True, the default is False.
Returns a customizable serialized URL string representation of a WHATWG URL object.

Although the ToString () method of the URL object and the href attribute can return a serialized string of URLs. However, neither can be customized. The Url.format (url[, Options]) method allows basic customization of the output.

For example:

const { URL } = require(‘url‘);const myURL = new URL(‘https://a:[email protected]你好你好?abc#foo‘);console.log(myURL.href);  // 输出 https://a:[email protected]/?abc#fooconsole.log(myURL.toString());  // 输出 https://a:[email protected]/?abc#fooconsole.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));  // 输出 ‘https://你好你好/?abc‘
4. New URL (input[, base])

Browser-compatible URL class, implemented according to the WHATWG URL standard.

Note: Depending on the convention of the browser, all properties of the URL object are implemented as getter and setter on the prototype of the class, not as data properties of the object itself. Therefore, unlike [legacy urlobjects][], using the DELETE keyword on any property of a URL object (such as delete Myurl.protocol,delete myurl.pathname, etc.) has no effect, but still returns true.

Parameters:

Input: Parsed entry URL
Base: If "input" is a relative URL, the base URL to resolve

Function: Creates a new URL object by parsing input into base. If base is a string, the resolution method is the same as the new URL (base).

For example:

const { URL } = require(‘url‘);const myURL = new URL(‘/foo‘, ‘https://example.org/‘);  // https://example.org/foo

If input or base is an invalid URLs, TypeError will be thrown. Note that the given value will be cast to a string. For example:

const { URL } = require(‘url‘);const myURL = new URL({ toString: () => ‘https://example.org/‘ });  // https://example.org/

Unicode characters that exist in the input host name are automatically converted to ASCII using the Punycode algorithm.

const { URL } = require(‘url‘);const myURL = new URL(‘https://你好你好‘);  // https://xn--6qqa088eba/
5.URLSearchParams

The Urlsearchparamsapi interface provides read and write access to the Urlquery section. The Urlsearchparams class can also be used alone with any of the following four constructors.

For example:

const { URL, URLSearchParams } = require(‘url‘);const myURL = new URL(‘https://example.org/?abc=123‘);console.log(myURL.searchParams.get(‘abc‘));// 输出 123myURL.searchParams.append(‘abc‘, ‘xyz‘);console.log(myURL.href);// 输出 https://example.org/?abc=123&abc=xyzmyURL.searchParams.delete(‘abc‘);myURL.searchParams.set(‘a‘, ‘b‘);console.log(myURL.href);// 输出 https://example.org/?a=bconst newSearchParams = new URLSearchParams(myURL.searchParams);// 上面的代码等同于// const newSearchParams = new URLSearchParams(myURL.search);newSearchParams.append(‘a‘, ‘c‘);console.log(myURL.href);// 输出 https://example.org/?a=bconsole.log(newSearchParams.toString());// 输出 a=b&a=c// newSearchParams.toString() 被隐式调用myURL.search = newSearchParams;console.log(myURL.href);// 输出 https://example.org/?a=b&a=cnewSearchParams.delete(‘a‘);console.log(myURL.href);// 输出 https://example.org/?a=b&a=c
6. DOMAINTOASCII (domain)

Returns the Punycode ASCII serialized domain. If domain is an invalid domain name, an empty string is returned.
It executes the inverse of the Url.domaintounicode ().

const url = require(‘url‘);console.log(url.domainToASCII(‘espa?ol.com‘));  // 输出 xn--espaol-zwa.comconsole.log(url.domainToASCII(‘中文.com‘));  // 输出 xn--fiq228c.comconsole.log(url.domainToASCII(‘xn--i?valid.com‘));  // 输出空字符串
7. Domaintounicode (Domain)

Returns the Unicode serialized domain. If domain is an invalid domain name, an empty string is returned.

It executes the inverse of the url.domaintoascii ().

const url = require(‘url‘);console.log(url.domainToUnicode(‘xn--espaol-zwa.com‘));  // 输出 espa?ol.comconsole.log(url.domainToUnicode(‘xn--fiq228c.com‘));  // 输出 中文.comconsole.log(url.domainToUnicode(‘xn--i?valid.com‘));  // 输出空字符串

# URL Common methods in node parsing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.