Writing a custom URL shortener function in JavaScript


Problem

We are required to write two JavaScript functions −

  • First function should take in a long url and return a short url that corresponds to it.
  • The second function should take in the short url and redirect to the original url.

Example

Following is the code −

 Live Demo

const url = 'https://www.google.com/search?client=firefox-b-d&q=google+search';
const obj = {};
const urlShortener = (longURL = '') => {
   let shortURL = "short.ly/" + longURL.replace(/[^a-z]/g,'').slice(-4);
   if(!obj[shortURL]){
      obj[shortURL] = longURL;
   };
   return shortURL;
   }
   const urlRedirector = (shortURL = '') => {
   return obj[shortURL];
};
const short = urlShortener(url);
const original = urlRedirector(short);
console.log(short);
console.log(original);

Output

Following is the console output −

short.ly/arch
https://www.google.com/search?client=firefox-b-d&q=google+search

Updated on: 20-Apr-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements