📅  最后修改于: 2023-12-03 15:03:14.524000             🧑  作者: Mango
The urlObject.href
API in Node.js provides a way to get or set the complete URL string represented by a URL
object. It returns a formatted string that includes the protocol, host, port, path, query parameters, and fragment identifier.
To use the urlObject.href
API, you need to first create a URL
object using the url
module.
const { URL } = require('url');
// Parse a URL string
const myURL = new URL('https://www.example.com/path?param=value#fragment');
// Get the complete URL string
const href = myURL.href;
console.log(href);
Output:
https://www.example.com/path?param=value#fragment
Let's see a more detailed example of using the urlObject.href
API to manipulate a URL.
const { URL } = require('url');
// Create a URL object
const myURL = new URL('https://www.example.com');
// Modify the URL
myURL.pathname = '/new-path';
myURL.searchParams.append('param1', 'value1');
// Get the complete URL string
const href = myURL.href;
console.log(href);
Output:
https://www.example.com/new-path?param1=value1
The urlObject.href
property returns the URL string in its entirety, including the protocol (e.g., 'http://' or 'https://'), the host name, any specified port number, path, query parameters, and fragment identifier.
Note that when setting the urlObject.href
property, it updates the entire URL. Any changes made to individual components (such as protocol
, host
, pathname
, search
, or hash
) after setting href
will be ignored.
The urlObject.href
API in Node.js provides a convenient way to get or set the complete URL string represented by a URL
object. It is useful for manipulating URLs and generating formatted strings for various purposes.