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:
href
: The URL string.protocol
: The protocol (e.g.,http
,https
,ftp
, etc.).host
: The hostname (e.g.,example.com
).pathname
: The path (e.g.,/path/to/resource
).search
: The query string (e.g.,?param=value
).hash
: The fragment (e.g.,#anchor
).toString()
: Returns the URL string.toString()
with no arguments: Returns the URL string with the protocol and host included.toString()
withincludeProtocol
set tofalse
: Returns the URL string without the protocol.
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