Computer >> Computer tutorials >  >> Programming >> Javascript

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 −

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