# Preparing encoding and decoding algorithms for shortening URLs in JavaScript

We often come through services like bit.ly and tinyurl which takes in any url and (usually one bigger in length), performs some encryption algorithm over it and returns a very short url. And similarity when we try to open that tiny url, it again runs some decryption algorithm over it and converts the short url to the original one opens the link for us.

We are also required to perform the same task. We are actually required to write two functions −

• encrypt() --> it will take in the original url and return to us a short unique ur.

• decrypt() --> it will take in the short url, will have no prior idea about the original url and convert it to the original url.

## Example

The code for this will be −

Live Demo

const url = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript';
const encrypt = (longUrl) => {
const encodedUrl = Buffer.from(longUrl, 'binary').toString('base64');
return "http://mydemo.com/" + encodedUrl;
};
const decrypt = function(shortUrl) {
let encodedUrl = shortUrl.split('mydemo.com/')[1];
return Buffer.from(encodedUrl, 'base64').toString();
};
const encrypted = encrypt(url);
const decrypted = decrypt(encrypted);
console.log(encrypted);
console.log(decrypted);

## Output

And the output in the console will be −

http://mydemo.com/aHR0cHM6Ly9kZXZlbG9wZXIubW96aWxsYS5vcmcvZW4tVVMvZG9jcy9XZWIvSmF2YVNjcmlwdA==
https://developer.mozilla.org/en-US/docs/Web/JavaScript