

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Create a custom toLowerCase() function in JavaScript
- Implementing a custom function like Array.prototype.filter() function in JavaScript
- How to decode a URL using JavaScript function?
- How to encode a URL using JavaScript function?
- Implementing custom function like String.prototype.split() function in JavaScript
- Create HTML Document with Custom URL for the document in JavaScript
- JavaScript - Redirect a URL
- Number prime test in JavaScript by creating a custom function?
- JavaScript - Writing a string function to replace the kth appearance of a character
- How to define custom sort function in JavaScript?
- Implement a custom function similar to Array.prototype.includes() method using JavaScript
- How to create a custom function similar to find() method in JavaScript?
- Remove duplicate items from an array with a custom function in JavaScript
- Custom len() Function In Python
- Writing a For Loop to Evaluate a Factorial - JavaScript
Advertisements