minimized programming code

JavaScript: the differences between escape(), encodeURI(), and encodeURIComponent()

Written by

in

In JavaScript, escape(), encodeURI(), and encodeURIComponent() are three functions used to encode strings for different purposes. Each function serves a distinct purpose, and it’s essential to understand their differences:

escape()

The escape() function is used to encode a string so that it can be safely included in a URL query string. It encodes special characters, except for alphanumeric characters and the following set of symbols: @*_+-./. The main drawback of escape() is that it does not encode all characters, and it’s considered deprecated in favor of encodeURIComponent().

Example:

const originalString = "Hello, World!";
const encodedString = escape(originalString);
console.log(encodedString); // "Hello%2C%20World%21"

encodeURI()

The encodeURI() function is used to encode a complete URI (Uniform Resource Identifier) but leaves the special characters used in the query string (?, &, =, etc.) untouched. It is primarily used to encode the main part of a URL, such as the protocol, domain, and path.

Example:

const originalURI = "https://www.example.com/my page.html?name=John Doe";
const encodedURI = encodeURI(originalURI);
console.log(encodedURI); // "https://www.example.com/my%20page.html?name=John%20Doe"

encodeURIComponent()

The encodeURIComponent() function is used to encode a component of a URI, such as a query parameter, fragment identifier, or any part that needs to be included in the query string. Unlike encodeURI(), this function encodes all special characters to ensure they are safely passed as parameters in a URL.

Example:

const originalParameter = "John Doe";
const encodedParameter = encodeURIComponent(originalParameter);
console.log(encodedParameter); // "John%20Doe"

In summary

Use escape() for encoding a string to be safely included in a query string, but it’s deprecated and not recommended for general use.

Use encodeURI() for encoding a complete URI (protocol, domain, path) but not the query string parameters.

Use encodeURIComponent() for encoding individual components (e.g., query parameters) of a URI to ensure all special characters are encoded properly. This is the most commonly used encoding function for URLs.

Foto von Markus Spiske auf Unsplash


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *