Preparing encoding and decoding algorithms for shortening URLs in JavaScript

JavascriptWeb DevelopmentFront End Technology

We often come through services like 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.


The code for this will be −

 Live Demo

const url = '';
const encrypt = (longUrl) => {
   const encodedUrl = Buffer.from(longUrl, 'binary').toString('base64');
   return "" + encodedUrl;
const decrypt = function(shortUrl) {
   let encodedUrl = shortUrl.split('')[1];
   return Buffer.from(encodedUrl, 'base64').toString();
const encrypted = encrypt(url);
const decrypted = decrypt(encrypted);


And the output in the console will be −
Updated on 03-Mar-2021 08:42:40