• Node.js Video Tutorials

NodeJS - url.username property



The NodeJS url.username property of URL class gets and sets the username of the provided URL. Invalid URL characters will be percent-encoded if they appear in the value assigned to the username property. The selection of characters to percent-encode may differ slightly from what the url.parse() and url.format() methods would produce.

There are several utilities for URL resolution and parsing provided by the Node.js URL module.

Syntax

Following is the syntax of the NodeJS username property of URL class

URL.username

Parameters

This method does not accept any parameters.

Return Value

This property gets and sets the username portion of the URL.

Example

If we assign a complete URL to the NodeJS url.username property, it will get the username portion of the URL.

In the following example, we are trying to get the username segment of the provided URL.

const http = require('url');

const myURL = new URL('https://Nikhil:hyd@tutorialspoint.com');
console.log("Username portion of the URL is: " + myURL.username);

Output

After executing the above program, the username property gets the username segment from the provided URL.

Username portion of the URL is: Nikhil

Example

The username property allows to set a valid value to the username segment in the given URL.

In the program below, we are trying to set a value to the username segment in the input URL.

const http = require('url');

const myURL = new URL('https://Nikhil:hyd@tutorialspoint.com');
console.log("The URL: " + myURL.href);
console.log("Username portion of the URL is: " + myURL.username);

myURL.username = "Nikhilesh";
console.log("Trying to change the username to - " + myURL.username);
console.log("The URL after modifying: " + myURL.href);

Output

As we can see in the output below, the username segment of the input URL is modified

The URL: https://Nikhil:hyd@tutorialspoint.com/
Username portion of the URL is: Nikhil

Trying to change the username to - Nikhilesh
The URL after modifying: https://Nikhilesh:hyd@tutorialspoint.com/

Example

If any invalid URL characters are appeared in the username portion of the URL, those characters will be percent-encoded.

In the following example, we are assigning an URL with invalid characters in username portion.

const http = require('url');

const myURL = new URL('https://Ni`khi`l:hyd@tutorialspoint.com');
console.log("The URL: " + myURL.href);
console.log("Username portion of the URL is: " + myURL.username);

Output

As we can see in the output, the invalid characters in the URL got percent-encoded.

The URL: https://Ni%60khi%60l:hyd@tutorialspoint.com/
Username portion of the URL is: Ni%60khi%60l
nodejs_url_module.htm
Advertisements