How to Get URL in TypeScript
In modern web development, working with URLs is a common requirement. TypeScript, a typed superset of JavaScript, offers several ways to handle and extract information from URLs. Understanding how to get and manipulate URLs in TypeScript is crucial for building robust web applications, whether it's for handling routing, making API calls, or parsing query parameters. This blog will explore the fundamental concepts, usage methods, common practices, and best practices for getting URLs in TypeScript.
Table of Contents#
Fundamental Concepts#
URL Object in JavaScript and TypeScript#
In JavaScript and TypeScript, the URL object provides a convenient way to parse, construct, normalize, and encode URLs. It is part of the Web API and is available in modern browsers and Node.js environments. The URL constructor takes a URL string as an argument and returns a URL object with various properties and methods to access different parts of the URL.
Here are some important properties of the URL object:
href: The full URL string.protocol: The protocol scheme of the URL (e.g.,http:,https:).host: The host (hostname and port) of the URL.hostname: The hostname of the URL.port: The port number of the URL.pathname: The path of the URL.search: The query string of the URL, including the leading?.hash: The fragment identifier of the URL, including the leading#.
Query Parameters#
Query parameters are used to pass data to a web server in the URL. They are appended to the end of the URL after a ? and are separated by &. For example, in the URL https://example.com/search?query=typescript&page=1, the query parameters are query=typescript and page=1.
Usage Methods#
Getting the Current URL in the Browser#
In a browser environment, you can use the window.location object to get the current URL. The window.location object provides properties similar to the URL object.
// Get the current URL
const currentUrl = window.location.href;
console.log('Current URL:', currentUrl);
// Get the protocol
const protocol = window.location.protocol;
console.log('Protocol:', protocol);
// Get the hostname
const hostname = window.location.hostname;
console.log('Hostname:', hostname);
// Get the pathname
const pathname = window.location.pathname;
console.log('Pathname:', pathname);
// Get the query string
const search = window.location.search;
console.log('Query string:', search);
// Get the hash
const hash = window.location.hash;
console.log('Hash:', hash);Parsing a URL Using the URL Object#
You can use the URL constructor to parse a URL string and access its different parts.
const urlString = 'https://example.com/search?query=typescript&page=1';
const url = new URL(urlString);
// Get the full URL
const href = url.href;
console.log('Full URL:', href);
// Get the protocol
const protocol = url.protocol;
console.log('Protocol:', protocol);
// Get the host
const host = url.host;
console.log('Host:', host);
// Get the pathname
const pathname = url.pathname;
console.log('Pathname:', pathname);
// Get the query string
const search = url.search;
console.log('Query string:', search);
// Get the hash
const hash = url.hash;
console.log('Hash:', hash);
// Get a specific query parameter
const query = url.searchParams.get('query');
console.log('Query parameter:', query);
// Get all query parameters
const searchParams = url.searchParams;
for (const [key, value] of searchParams) {
console.log(`${key}: ${value}`);
}Working with Relative URLs#
You can also use the URL constructor to resolve relative URLs.
const baseUrl = 'https://example.com';
const relativeUrl = '/about';
const resolvedUrl = new URL(relativeUrl, baseUrl);
console.log('Resolved URL:', resolvedUrl.href);Common Practices#
Handling Query Parameters#
When working with query parameters, it's common to need to get, set, or delete them. You can use the URLSearchParams object, which is available through the searchParams property of the URL object.
const url = new URL('https://example.com/search?query=typescript&page=1');
// Get a query parameter
const query = url.searchParams.get('query');
console.log('Query parameter:', query);
// Set a query parameter
url.searchParams.set('page', '2');
console.log('Updated URL:', url.href);
// Delete a query parameter
url.searchParams.delete('query');
console.log('URL after deletion:', url.href);Checking if a URL is Valid#
You can use a try-catch block when creating a URL object to check if a URL is valid.
function isValidUrl(urlString: string): boolean {
try {
new URL(urlString);
return true;
} catch (error) {
return false;
}
}
const validUrl = 'https://example.com';
const invalidUrl = 'invalid-url';
console.log('Is valid URL:', isValidUrl(validUrl));
console.log('Is invalid URL:', isValidUrl(invalidUrl));Best Practices#
Error Handling#
When working with URLs, it's important to handle errors properly. For example, if you try to create a URL object with an invalid URL, it will throw an error. You should use try-catch blocks to handle these errors gracefully.
try {
const url = new URL('invalid-url');
} catch (error) {
console.error('Invalid URL:', error);
}Security Considerations#
When working with user-supplied URLs or query parameters, it's important to validate and sanitize them to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. You can use libraries like validator.js to validate URLs and sanitize input.
import validator from 'validator';
const userInputUrl = 'https://example.com';
if (validator.isURL(userInputUrl)) {
console.log('Valid URL');
} else {
console.log('Invalid URL');
}Code Readability and Maintainability#
Use descriptive variable names when working with URLs and query parameters. This will make your code more readable and easier to maintain.
const apiBaseUrl = 'https://api.example.com';
const searchEndpoint = '/search';
const query = 'typescript';
const page = 1;
const searchUrl = new URL(searchEndpoint, apiBaseUrl);
searchUrl.searchParams.set('query', query);
searchUrl.searchParams.set('page', page.toString());
console.log('Search URL:', searchUrl.href);Conclusion#
In this blog, we have explored how to get URLs in TypeScript. We covered the fundamental concepts of the URL object and query parameters, different usage methods for getting and parsing URLs, common practices for handling query parameters and validating URLs, and best practices for error handling, security, and code readability. By understanding these concepts and techniques, you can effectively work with URLs in your TypeScript projects.