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:
// 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