Asked 7 years ago
4 Jan 2017
Views 1082
yogi

yogi posted

how to encode URL in JavaScript

how to encode URL in JavaScript

var url='www.second-domain.com/me-redirected';
var mainurl='http://www.first-domain.com/index.php?url='+url;


need to encode URL when passing it as query string in URL in javascript
ajamil

ajamil
answered May 4 '23 00:00

To encode a URL in JavaScript is by using the encodeURIComponent() function. This function takes a string as input and returns a URI-encoded version of the string.

Here's an example of how you can use the encodeURIComponent() function to encode a URL:


const url = 'https://www.example.com/search?q=some query';
const encodedUrl = encodeURIComponet(url);

console.log(encodedUrl); // Output: "https%3A%2F%2Fwww.example.com%2Fsearch%3Fq%3Dsome%20query"

In the example above, we have a URL with a query string that contains a space character. To encode this URL, we call the encodeURIComponent() function on the URL string and store the result in a new variable called encodedUrl.

The encodeURIComponent() function replaces certain characters in the input string with their corresponding percent-encoded values . For example, spaces are encoded as %20, colons are encoded as %3A, slashes are encoded as %2F, and so on.

Note that we're using the encodeURIComponet() function, which is similar to encodeURIComponent(), but it encodes fewer characters than encodeURIComponent(). In general, you should use encodeURIComponent() for encoding query parameters and encodeURI() for encoding entire URLs.
Post Answer