How to use URL and URLSearchParams Interfaces In Typescript

The URL interface represents an object providing methods for working with URLs. The URLSearchParams interface provides methods for working with the query string of a URL.

Syntax:

let url = new URL(urlString);
let params = new URLSearchParams(url.search);
params.append(name, value);
url.search = params.toString();

Example:

JavaScript
// Creating a URL object
let url = new URL("https://www.w3wiki.org");

// Adding query parameters
let params = new URLSearchParams(url.search);
params.append("search", "typescript tutorial");
params.append("page", "1");

// Updating the URL with encoded query parameters
url.search = params.toString();

// Logging the final encoded URL
console.log("The encoded URL is", url.toString());

Output:

The encoded URL is https://www.w3wiki.org/?search=typescript+tutorial&page=1


How to Encode URI in TypeScript?

When you are working with web applications in TypeScript, you often require encoding Uniform Resource Identifiers (URIs) in order to make sure that special characters are transmitted correctly across the internet. TypeScript which is a superset of JavaScript, gives you access to native JavaScript functions for URI encoding.

Here are some common approaches:

Table of Content

  • Using encodeURI() and encodeURIComponent()
  • Using escape() Function
  • Using URL and URLSearchParams Interfaces

Similar Reads

Using encodeURI() and encodeURIComponent()

TypeScript provides two methods for encoding URIs:...

Using escape() Function

The escape() function encodes a string by replacing certain characters with hexadecimal escape sequences. It is useful for encoding strings to be included in URLs....

Using URL and URLSearchParams Interfaces

The URL interface represents an object providing methods for working with URLs. The URLSearchParams interface provides methods for working with the query string of a URL....