Spread the love

How do I use JavaScript to get the base URL or the URL parameters?

When developing for the web, manipulating URLs is a common task, whether it’s retrieving the base URL or extracting URL parameters. Fortunately, these tasks can be accomplished with just a few lines of JavaScript code.

blue lake 1200

1. Get the Base URL

1. Get the Base URL

The base URL typically consists of the protocol, domain, and optionally the port and path (excluding query parameters and fragments). You can get it using the window.location object.

// Get the full URL
const fullUrl = window.location.href;
// Get the protocol (e.g., "http:")

const protocol = window.location.protocol;
// Get the host (e.g., "example.com")

const host = window.location.host;
// Get the path (e.g., "/path/to/page")

const pathname = window.location.pathname;
// Combine them to get the base URL

const baseUrl = `${protocol}//${host}${pathname}`;
console.log(baseUrl);
Screenshot 2024 08 21 204510

Alternatively, if you only want the base URL without the path:

const baseUrlWithoutPath = `${window.location.protocol}//${window.location.host}`;
console.log(baseUrlWithoutPath);
Screenshot 2024 08 21 204644

2. Get URL Parameters

You can get the URL parameters (also called query parameters) using the URLSearchParams object.

// Create a URLSearchParams object

const params = new URLSearchParams(window.location.search);
// Get a specific parameter by name

const paramValue = params.get('paramName'); // Replace 'paramName' with your parameter key
// Example: If the URL is https://example.com/page?name=John&age=30

console.log(params.get('name')); // Outputs: John

console.log(params.get('age')); // Outputs: 30

// Loop through all parameters
params.forEach((value, key) => {

console.log(`${key}: ${value}`);
});

Screenshot 2024 08 21 204736

Example:

If the URL is https://example.com/path/to/page?name=John&age=30:

  • Base URL: https://example.com/path/to/page
  • URL Parameters: name=John, age=30

techbloggerworld.com

Nagendra Kumar Sharma I Am Software engineer

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *