How to use encodeURI() and encodeURIComponent() In Typescript

TypeScript provides two methods for encoding URIs:

  • encodeURI(): The aim of this procedure is to encode the entire URI in order to modify characters, that are not permitted in a URI so that they become percentage-encoded but still maintain the URI’s building coding blocks.
  • encodeURIComponent(): Different from encodeURI(), this procedure was made for encoding separate URI constituents such as query parameters or fragments.

Most of the times encodeURI() is used to make sure that only a full URI is encoded, by changing characters such as those that cannot be used in a URI to their percent-encoded form, this way it will make sure that the URI remains correct and can be moved or saved securely.

Syntax:

encodeURI(uri: string): string

Example 1: Implementation to Encode URI Using encodeURI() Method.

JavaScript
// Define the original URI
const originalURI: string = "www.w3wiki.org";

// Encoding the URI
let encodedURI = encodeURI(originalURI);
console.log("The encoded URI is " + encodedURI);

Output:

The encoded URI is www.w3wiki.o%20rg

Example 2: Below code demonstrates how to encode/decode a URI component. The first part encodes string “w3wiki.org/:>” to create a URL, afterwards another URL is made by decoding provided URI component string. Lastly, both encoded and decoded URLs are logged into the console.

JavaScript
// Encoding the URI component
let encodedURIComponent = `https://www.${
  encodeURIComponent("w3wiki.org/:>")
}=`;

console.log("The encoded URI component is " 
             + encodedURIComponent);

Output:

The encoded URI component is https://www.w3wiki.org%2F%3A%3E=

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....

Contact Us