DEV Community

Jitendra
Jitendra

Posted on

Encode URL in Javascript

Did you know that each website and online resource has a unique URL for its address? Uniform Resource Locators, or URLs, can appear straightforward but contain numerous components and special characters, making them truly fairly complex.

Built-in JavaScript Encoding Functions

When It comes to encoding in JavaScript. It Gives to two functions to perform encoding encodeURIComponent() and encodeURI().

How to use encodeURI in JavaScript

This function is used for encoding the complete URI (Uniform Resource Identifier). A limitation of we can say feature of encodeURI is that it does not encode characters ~!@#$&*()=:/,;?+' .

Syntax:

const originalURI = "https://www.dev.to/search?q=Hello dev";
const encodedURI = encodeURI(originalURI);
console.log(encodedURI);
VM249:3 https://www.dev.to/search?q=Hello%20dev

Enter fullscreen mode Exit fullscreen mode

How to use encodeURIComponent in JavaScript

This function is used to encode complete URL (Uniform Resource Locator) instead of URI.

Syntax:

const originalURI = "https://www.dev.to/search?q=Hello dev";
const encodedURI = encodeURIComponent(originalURI);
console.log(encodedURI);
VM261:3 https%3A%2F%2Fwww.dev.to%2Fsearch%3Fq%3DHello%20dev
Enter fullscreen mode Exit fullscreen mode

You can use any online JavaScript code executor, browser console, or online URL encode tool to verify your encoding output.

Encoding vs Encryption

People frequently get confused between encoding and encryption. Although both are used to transform data but to serve different purposes and requirements.

Encoding: Encoding is used to transform data into specific format without maintaining security. It is easily reversible using appropriate method.

Encryption:: Encryption is used to protect data using complex algorithms. It ensures data confidentiality and security. Encrypted data is also reversible but only with the correct decryption key.

Top comments (0)