Javascript new url

In JavaScript, you can create a new URL object using the URL constructor or the new URL() syntax. Here are a few ways to do it:

Method 1: Using the URL constructor

const url = new URL('https://example.com/path/to/resource');

This creates a new URL object with the specified URL string.

Method 2: Using the new URL() syntax

const url = new URL('https://example.com/path/to/resource', 'https://example.com');

This creates a new URL object with the specified URL string and a base URL (in this case, https://example.com).

Method 3: Using the URL constructor with options

const url = new URL('https://example.com/path/to/resource', {
  protocol: 'https:',
  host: 'example.com',
  pathname: '/path/to/resource'
});

This creates a new URL object with the specified URL string and options.

Properties and methods

Once you have created a URL object, you can access its properties and methods to manipulate the URL. Some common properties and methods include:

Here are some examples:

const url = new URL('https://example.com/path/to/resource');

console.log(url.href); // Output: https://example.com/path/to/resource
console.log(url.protocol); // Output: https:
console.log(url.host); // Output: example.com
console.log(url.pathname); // Output: /path/to/resource
console.log(url.search); // Output: (empty string)
console.log(url.hash); // Output: (empty string)

console.log(url.toString()); // Output: https://example.com/path/to/resource
console.log(url.toString(true)); // Output: https://example.com/path/to/resource
console.log(url.toString(false)); // Output: /path/to/resource