Encode URL in JavaScript

javascript

In JavaScript, you can encode a URL using the encodeURIComponent() function. This function takes a string as input and returns a new string with all special characters encoded so that it can be safely used as a part of a URL.

Here is an example:

const url = "https://www.example.com/search?q=JavaScript&sort=recent";

const encodedUrl = encodeURIComponent(url);

console.log(encodedUrl); // "https%3A%2F%2Fwww.example.com%2Fsearch%3Fq%3DJavaScript%26sort%3Drecent"

In the above example, the encodeURIComponent() function is used to encode the url string. The resulting encoded URL can be used as a query parameter value or as a part of a URL.

Note that the encodeURIComponent() function does not encode the following characters: -, _, ., !, ~, *, ’, (, and ). If you need to encode these characters as well, you can use the encodeURI() function instead. However, encodeURI() does not encode the characters &, =, and ?, which have special meanings in a URL query string.