URL Objects in JavaScript

URL Objects in JavaScript

In JavaScript, the URL object is a built-in global object that provides utilities for handling and manipulating URLs. It allows you to parse, construct, and modify URL strings more easily compared to manually working with strings.

What is a URL Object?

The URL object represents an entire URL, including its components like the protocol, host, pathname, search, and hash. It allows you to interact with these components programmatically.

Creating a URL Object

You can create a URL object by passing a string URL to the URL constructor.

const url = new URL('https://www.example.com:8080/pathname/?search=query#hash'); console.log(url);

This creates a URL object that allows you to access various parts of the URL using properties and methods.

Properties of the URL Object

The URL object provides several properties that represent the different components of the URL:

  1. href: The entire URL (string representation).

    console.log(url.href); // "https://www.example.com:8080/pathname/?search=query#hash"
  2. protocol: The protocol/scheme of the URL (e.g., 'http:', 'https:', 'ftp:').

    console.log(url.protocol); // "https:"
  3. host: The hostname and port (e.g., 'www.example.com:8080').

    console.log(url.host); // "www.example.com:8080"
  4. hostname: The hostname (without the port).

    console.log(url.hostname); // "www.example.com"
  5. port: The port number (e.g., '8080').

    console.log(url.port); // "8080"
  6. pathname: The path portion of the URL (e.g., '/pathname').

    console.log(url.pathname); // "/pathname"
  7. search: The query string (including the leading ?), if present.

    console.log(url.search); // "?search=query"
  8. searchParams: A URLSearchParams object that allows easy manipulation of query parameters.

    console.log(url.searchParams); // URLSearchParams { 'search' => 'query' }
  9. hash: The fragment identifier (e.g., '#hash').

    console.log(url.hash); // "#hash"
  10. username and password: If the URL contains authentication credentials, these properties hold the username and password.

    const authUrl = new URL('https://username:password@www.example.com'); console.log(authUrl.username); // "username" console.log(authUrl.password); // "password"

Modifying URL Components

You can modify the URL components directly via the properties of the URL object:

url.hostname = 'newdomain.com'; url.pathname = '/newpath'; url.search = '?newsearch=newquery'; url.hash = '#newhash'; console.log(url.href); // "https://newdomain.com:8080/newpath?newsearch=newquery#newhash"

Using URLSearchParams to Manipulate Query Parameters

The searchParams property is a URLSearchParams object, which provides methods for working with the query string of the URL (i.e., the part after the ?).

Common Methods for URLSearchParams:

  • get(name): Returns the first value for the given parameter name.

    console.log(url.searchParams.get('search')); // "query"
  • set(name, value): Sets the value of a query parameter, replacing any existing value.

    url.searchParams.set('search', 'newquery'); console.log(url.href); // "https://newdomain.com:8080/newpath?search=newquery#newhash"
  • append(name, value): Appends a new value for the given parameter name (if it already exists).

    url.searchParams.append('search', 'anotherquery'); console.log(url.href); // "https://newdomain.com:8080/newpath?search=newquery&search=anotherquery#newhash"
  • delete(name): Deletes the query parameter.

    url.searchParams.delete('search'); console.log(url.href); // "https://newdomain.com:8080/newpath#newhash"
  • has(name): Checks if a query parameter exists.

    console.log(url.searchParams.has('search')); // false
  • toString(): Returns the query string (the part after ?).

    console.log(url.searchParams.toString()); // "search=newquery&search=anotherquery"

Example: Working with URLSearchParams

const myUrl = new URL('https://example.com'); myUrl.searchParams.append('page', 1); myUrl.searchParams.append('sort', 'asc'); console.log(myUrl.href); // "https://example.com/?page=1&sort=asc" myUrl.searchParams.set('page', 2); console.log(myUrl.href); // "https://example.com/?page=2&sort=asc" myUrl.searchParams.delete('sort'); console.log(myUrl.href); // "https://example.com/?page=2"

URL Object Methods

  1. toString(): Returns the entire URL as a string.

    console.log(url.toString()); // "https://newdomain.com:8080/newpath?search=newquery#newhash"
  2. toJSON(): Returns the URL as a string (same as toString()).

    console.log(url.toJSON()); // "https://newdomain.com:8080/newpath?search=newquery#newhash"
  3. origin: Returns the origin of the URL (i.e., the protocol, hostname, and port).

    console.log(url.origin); // "https://newdomain.com:8080"

Practical Use Case: Creating URLs Dynamically

Suppose you're building a website where users can filter content with various query parameters. Using the URL object allows you to easily construct the URL with the necessary parameters.

Example: Dynamic URL Creation

function createFilteredUrl(baseUrl, filters) { const url = new URL(baseUrl); for (let key in filters) { url.searchParams.set(key, filters[key]); } return url.href; } const baseUrl = 'https://www.example.com/products'; const filters = { category: 'electronics', price: '100-500', sort: 'price-asc' }; console.log(createFilteredUrl(baseUrl, filters)); // Output: "https://www.example.com/products?category=electronics&price=100-500&sort=price-asc"

Example: Validating URL

You can use the URL constructor to validate if a URL is well-formed.

function isValidUrl(urlString) { try { new URL(urlString); return true; } catch (e) { return false; } } console.log(isValidUrl('https://www.example.com')); // true console.log(isValidUrl('invalid-url')); // false

Summary

  • The URL object provides an easy way to work with and manipulate URLs in JavaScript.
  • You can create a URL object by passing a URL string to the URL constructor.
  • It offers properties like href, protocol, hostname, pathname, search, and hash for accessing different components of a URL.
  • The searchParams property is a URLSearchParams object that allows for easy manipulation of the query string.
  • The URL object is useful for tasks such as validating, parsing, and dynamically generating URLs.
Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close